【发布时间】:2018-12-20 16:53:19
【问题描述】:
我需要在我的应用程序运行时和启动时处理通过 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);
关于我缺少什么的任何想法?
【问题讨论】:
-
我不确定挂起的 Intent 是否真的会启动 JobIntentService,因为它永远不会“排队”工作要做,我遇到了同样的问题,并通过使用 PendingIntent 打开 BroadcastReceiver 解决了这个问题已注册并且 Receivers onReceive(Intent) 方法用于启动 JobIntentService.enqueueWork(intent);
-
谢谢。我仍然不明白为什么它不起作用,但我按照你的建议让它工作了。对于面临相同问题的其他人:(1)我无法调用 BroadcastReceiver,除非我创建了一个专门针对它的意图(通过它的类); (2) 我发现我需要按照建议从 BroadcastReceiver 显式调用静态函数 enqueueWork(intent),而不是尝试提出由 JobIntentService 处理的意图
-
@Brandon 的建议不起作用。我正在使用 PendingIntent 并且没有调用 BroadcastReceiver。
-
你能把你的代码发给我吗@EduardoXavier