首页 文章

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

提问于
浏览
9

在我的应用程序中,我有一个通知按钮,使用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上的丑陋通知 .

EDIT: Below is the code I ended up with besides the straight forward conversion of the IntentService to a 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);

1 回答

  • 17

    我怎么能做到这一点?

    使用 BroadcastReceivergetBroadcast() PendingIntent ,然后让接收器从 onReceive() 方法调用 JobIntentService enqueueWork() 方法 . 我试过这个,但AFAIK应该可以 .

相关问题