【发布时间】:2019-07-07 14:31:08
【问题描述】:
我正在尝试定期运行服务,即使应用程序被终止或使用 workManager 在后台运行。
我的 RequestService 类如下:-
public class RequestService extends Worker {
public RequestService(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
displayNotification("MY Worker", "Background work Started");
Log.i("BackJob","Running");
return Result.SUCCESS;
}
private void displayNotification(String title, String task){
NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("MyApp","My Notifications",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder notification = new NotificationCompat.Builder(getApplicationContext(), "My Notifications").
setContentTitle(title).setContentText(task)
.setSmallIcon(R.mipmap.ic_launcher);
notificationManager.notify(130, notification.build());
}}
这是主要的活动代码:-
final PeriodicWorkRequest WorkReq = new PeriodicWorkRequest.Builder(RequestService.class,15,TimeUnit.MINUTES).build();
WorkManager.getInstance().enqueue(WorkReq);
问题是如果应用程序被杀死或在后台,那么 workmanager 就会停止工作。 我正在使用 android 版本 pie 的三星设备上对此进行测试。
PS :- 如果应用程序已打开,那么我会在 15 分钟后连续看到通知....但是一旦我关闭应用程序.....它就会停止工作......并且没有更多通知
【问题讨论】:
-
你能看一下WorkManager的codelab源码吗?它实现了一些显示通知的 Worker 类。它包括一个解决相同问题的
makeStatusNotification:github.com/googlecodelabs/android-workmanager/blob/… -
您找到解决方案了吗?我面临着类似的问题。
标签: android android-notifications android-workmanager