从PendingIntent(通知按钮)启动JobIntentService?

21

在我的应用程序中,我有一个通知按钮,它使用IntentService在后台触发一个短网络请求。在这里显示GUI没有意义,这就是为什么我使用服务而不是活动的原因。请参见下面的代码。

// Build the Intent used to start the NotifActionService
Intent buttonActionIntent = new Intent(this, NotifActionService.class);
buttonActionIntent.setAction(NotifActionService.ACTION_SEND_CONFIRM);
buttonActionIntent.putExtra(NotifActionService.EXTRA_CONFIRM_ID, confirmId);
buttonActionIntent.putExtra(NotifActionService.EXTRA_NOTIF_ID, notifId);

// Build the PendingIntent used to trigger the action
PendingIntent pendingIntentConfirm = PendingIntent.getService(this, 0, buttonActionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

这个方案很可靠,但由于Android 8.0中的新后台限制,我想改为使用JobIntentService。更新服务代码本身似乎非常简单,但我不知道如何通过PendingIntent启动它,而通知操作需要用到它。

我该如何做到这一点?

是否最好改用普通服务,并在API级别26+上使用PendingIntent.getForegroundService(...),并在API级别25及以下使用当前代码?这将要求我手动处理唤醒锁、线程,并在Android 8.0+上产生一个丑陋的通知。

编辑:除了将IntentService直接转换为JobIntentService之外,下面是我最终采用的代码。

广播接收器只需将意图类更改为我的JobIntentService并运行其enqueueWork方法:

public class NotifiActionReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        intent.setClass(context, NotifActionService.class);
        NotifActionService.enqueueWork(context, intent);
    }
}

原始代码的修改版本:

// Build the Intent used to start the NotifActionReceiver
Intent buttonActionIntent = new Intent(this, NotifActionReceiver.class);
buttonActionIntent.setAction(NotifActionService.ACTION_SEND_CONFIRM);
buttonActionIntent.putExtra(NotifActionService.EXTRA_CONFIRM_ID, confirmId);
buttonActionIntent.putExtra(NotifActionService.EXTRA_NOTIF_ID, notifId);

// Build the PendingIntent used to trigger the action
PendingIntent pendingIntentConfirm = PendingIntent.getBroadcast(this, 0, buttonActionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
1个回答

33
我怎样才能实现这个?
使用一个BroadcastReceiver和getBroadcast() PendingIntent,然后让接收器从其onReceive()方法调用JobIntentService的enqueueWork()方法。我承认我没有尝试过这个,但据我所知,它应该可以工作。

好的,那应该可以。我会试一下,如果它确实解决了我的问题并且在新旧平台上都能正常工作,我会将您的答案标记为已接受的。 - blunden
1
你成功了吗?如果是的话,能否请您发布一个示例?谢谢。 - tomseitz
你们能否举个例子,说明一下你们是如何实现的呢?我想在我的应用程序小部件上尝试。 - Muhammad Mehdi Raza
@MuhammadMehdiRaza:“我能做到像每次屏幕解锁时更新我的应用程序小部件,例如screen_on操作吗?” - 据我所知,在Android 8.0+上不行,因为ACTION_USER_PRESENT未列在隐式广播例外名单中。 - CommonsWare
1
@LoveForDroid:我不确定你问题中的“它”是什么,但是我的回答中所有内容都应该有效。 - CommonsWare
显示剩余3条评论

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