问题描述
我正在尝试在我的应用程序中创建以下功能:
我需要在后台检查新通知(即即使应用程序关闭时)。如果应用程序正在运行,我想通知我的活动。如果应用程序未运行,则应显示通知。 用户可以设置检查通知的频率。 通知检查必须在设备重启后(或用户安装应用程序并登录时)自行启动。
我已经花了半天时间。
我注册了一个 broadcastReceiver 来捕获设备的成功启动 (BOOT_COMPLETE)。
此外,我仍然不明白接下来应该使用什么(Services 或 Worker 或其他)。 如何每 x 分钟调用一次检查(如果用户在设置中更改分钟,则更改分钟)。
我可能已经搜索了整个互联网,但仍然找不到任何可以帮助我的东西。我也阅读了有关服务和工作线程的内容,但我仍然不知道该使用什么。
我很乐意提供任何帮助
顺便说一句。我通过使用 Retrofit 调用 API 来获得通知(NO Firebase):
private void callAPI(String request) {
call = apiInterface.getAPIData(request);
call.enqueue(new Callback<APIResponse>() {
@Override
public void onResponse(@NotNull Call<APIResponse> call,@NotNull Response<APIResponse> response) {
....
}
@Override
public void onFailure(@NotNull Call<APIResponse> call,@NotNull Throwable t) {
System.out.println(t.toString());
}
});
}
编辑:通知检查必须在用户注销时结束。如果用户再次登录,通知检查再次开始
解决方法
为了在后台接收推送通知,我使用了 FirebaseMessagingService
的子类。但是,这取决于推送的类型:包含通知、数据或两者。请参阅FCM documentation。
好的,我现在正在测试以下实现,目前看起来不错
引导接收器:
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context,Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) && !getEmail(context).isEmpty())
startService(context);
}
}
服务工具:
public class utils {
private static final String TAG = "NotificationsChecker";
public static void startService(Context context) {
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build();
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(NotificationsWorker.class,getNotificationsFrequency(context),TimeUnit.MINUTES)
.addTag(TAG)
.setConstraints(constraints)
.build();
WorkManager.getInstance(context).enqueueUniquePeriodicWork(TAG,ExistingPeriodicWorkPolicy.REPLACE,workRequest);
}
public static void stopService(Context context) {
WorkManager.getInstance(context).cancelAllWorkByTag(TAG);
}
public static void restartService(Context context) {
stopService(context);
startService(context);
}
}
和通知工作人员:
public class NotificationsWorker extends Worker {
private final NotificationsHelper notificationsHelper;
public NotificationsWorker(@NonNull Context context,@NonNull WorkerParameters workerParams) {
super(context,workerParams);
Log.d("Notifications worker","Worker initiated");
this.notificationsHelper = new NotificationsHelper(context,APIUtils.getAPIService(),newNotifications -> {
if (newNotification == null) {
Log.d("Notifications checker","newNotification is null");
}
else if (newNotification.getValue() != null && !newNotification.getValue())
Log.d("Notifications checker","newNotification is not null");
else
Log.d("Notifications checker","newNotification is undefined");
//newNotification.setValue(newNotifications);
});
}
@NonNull
@Override
public Result doWork() {
notificationsHelper.prepareAPI();
return Result.success();
}
}