首页 > 解决方案 > 在 JobIntentService 中未调用 onHandleWork()

问题描述

我需要在我的应用程序运行时和启动时处理通过 AlarmManager 发布的意图。我编写了 JobIntentService 的子类来处理意图,但它没有按预期工作:未调用 onHandleWork。

当处理程序是 IntentService 时,我的实现工作,除了在启动时,由于后台服务的限制。因此,我尝试改用 JobIntentService。

public class MyJobIntentService extends JobIntentService
{
    public int onStartCommand(@Nullable Intent intent, int flags, int startId)
    {
        // This gets called with the intent given to AlarmManager
        return super.onStartCommand(intent, flags, startId);
    }

    public static void enqueueWork(Context context, Intent work)
    {
        // Not called
        enqueueWork(context, NotificationService.class, JOB_ID, work);
    }

    public void onHandleWork(@NonNull Intent intent)
    {
        // Not called
        ...
    }

    // No other methods overridden
}

onStartCommand 被调用。文档说这种方法:

进程在作为 pre-O 服务运行时启动命令,将它们排入队列以便稍后在 onHandleWork(Intent) 中调度。

我不知道“稍后”在这里应该是什么意思,但实际上并没有调用 onHandleWork,即使已经以预期的意图调用了 onStartCommand。

我已经阅读了类似问题的答案,并确保我不会覆盖其他方法。我还为我认为正确的服务创建了一个清单条目 - 否则不会调用 onStartCommand。

这就是我创建与 AlarmManager 一起使用的 PendingIntent 的方式:

Intent myIntent = new Intent( myContext, MyJobIntentService.class);
...
PendingIntent pendingIntent = PendingIntent.getService( mContext, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
myAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);

关于我所缺少的任何想法?

标签: androidjobintentservice

解决方案


你可以试试这个建议。此外,您可能需要检查您的 AndroidManifest.xml 以android.permission.BIND_JOB_SERVICE获得许可。


推荐阅读