在我的应用程序中,我有一个通知按钮,它使用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);
ACTION_USER_PRESENT
未列在隐式广播例外名单中。 - CommonsWare