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

blu*_*den 13 android android-8.0-oreo

在我的应用程序中,我有一个通知按钮,使用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);
Run Code Online (Sandbox Code Playgroud)

这工作可靠但是由于Android 8.0中的新背景限制使我想要转移到JobIntentService.更新服务代码本身似乎非常简单,但我不知道如何通过PendingIntent启动它,这是通知操作所需要的.

我怎么能做到这一点?

是否更好地转移到普通服务并在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

修改后的原始代码版本:

// 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);
Run Code Online (Sandbox Code Playgroud)

Com*_*are 23

我怎么能做到这一点?

使用a BroadcastReceiver和a getBroadcast() PendingIntent,然后让接收者JobIntentService enqueueWork()从其onReceive()方法中调用方法.我承认我没有尝试过这个,但AFAIK应该可以.

  • 我可以确认这适用于运行Oreo的Pixel 2 (3认同)