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

Starting JobIntentService from PendingIntent (Notification button)?

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

// 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 之外,下面是我最终得到的代码。

BroadcastReceiver 将意图 class 更改为我的 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);

How could I accomplish this?

使用 BroadcastReceivergetBroadcast() PendingIntent,然后让接收方从其 onReceive() 方法中调用 JobIntentService enqueueWork() 方法.我承认我没有尝试过这个,但据我所知它应该有效。