当应用程序在后台时,Workmanager无法正常工作

3
我正在尝试使用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);

问题在于如果应用程序被杀死或在后台运行,则工作管理器停止工作。 我正在三星设备上测试此问题,其Android版本为Pie。
附言:如果应用程序处于打开状态,则在15分钟后我会持续收到通知....但是一旦我关闭应用程序....它就停止工作了....没有更多的通知。

请你看一下WorkManager代码实验室的源代码吗?它实现了一些显示通知的Worker类。其中包括一个makeStatusNotification函数,解决了相同的问题:https://github.com/googlecodelabs/android-workmanager/blob/ec9e065086ce5912f3a3ae7cbd039ea6da086531/app/src/main/java/com/example/background/workers/WorkerUtils.java#L60 - pfmaggi
你有解决办法吗?我遇到了类似的问题。 - Usman Rana
3个回答

2
您可以使用前台服务来实现此功能,前台服务可以在应用程序处于后台时工作。
请将此方法添加到downork方法中。
setForegroundAsync(createForegroundInfo(progress));

workermanager 类中重写此方法。

 @NonNull
    private ForegroundInfo createForegroundInfo(@NonNull String progress) {

        Context context = getApplicationContext();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan = new NotificationChannel("1", "channelName", NotificationManager.IMPORTANCE_NONE);
            chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            assert manager != null;
            manager.createNotificationChannel(chan);
        }

        Notification notification = new NotificationCompat.Builder(context, "1")
                .setContentTitle("title")
                .setTicker("title")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setOngoing(true)
                .build();

        return new ForegroundInfo(1,notification);
    }

现在你的应用程序将在后台运行。

有人试过这个解决方案吗?尤其是在Android 9和10上? - Aziz

1
根据这里提供的PeriodicWorkRequest.Builder官方文档,intervalMillis必须大于或等于PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS。
此值当前设置为900000毫秒,即15分钟。

参考帖子...那是我正在使用的...15分钟,TimeUnit.MINUTES - Jaspreet Singh
好的,你在其他设备上测试过吗?三星设备有一些测试问题。 - GOVIND DIXIT
是的,仍然没有成功。 - Jaspreet Singh

0
这是一个工作示例,目前显示有关操作系统版本的任何通知。但似乎问题可能与NotificationManagerCompat中的notify方法有关。
private void makeStatusNotification(String message, Context context) {

    String channelId = context.getString(R.string.worker_sync_notif_channel_id);

    // Make a channel if necessary
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // Create the NotificationChannel, but only on API 26+
        CharSequence name = context.getString(R.string.worker_sync_notif_channel_name);
        String description = context.getString(R.string.worker_sync_notif_channel_description);
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel channel = new NotificationChannel(channelId, name, importance);
        channel.setDescription(description);
        // Add the channel
        NotificationManager notificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }

    // Create the notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.ic_cloud_upload)
            .setContentTitle(context.getString(R.string.worker_sync_notif_title))
            .setContentText(context.getString(R.string.worker_sync_notif_subject))
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(message))
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setVibrate(new long[0])
            .setAutoCancel(true);

    // Show the notification
    NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build());
}

抱歉回复晚了......感谢您的答案......我能够显示通知,但是当应用程序在后台时,工作管理器仍会停止定期请求。 - Jaspreet Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接