在我的应用程序中,我有一个通知按钮,该按钮使用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启动它,这是Notification Actions所需要的。

我怎样才能做到这一点?

改用普通服务并在API级别26+上使用PendingIntent.getForegroundService(...)以及在API级别25及以下使用当前代码会更好吗?那将需要我手动处理唤醒锁,线程,并在Android 8.0+上导致难看的通知。

编辑:除了将IntentService直接转换为JobIntentService外,下面是我最后得到的代码。

BroadcastReceiver只是将intent类更改为我的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);

最佳答案



使用BroadcastReceivergetBroadcast() PendingIntent,然后让接收方从其JobIntentService方法调用enqueueWork() onReceive()方法。我承认我还没有尝试过,但是AFAIK应该可以。

关于android - 从PendingIntent(通知按钮)启动JobIntentService?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46139861/

10-10 17:07