web-dev-qa-db-ja.com

PendingIntent(通知ボタン)からJobIntentServiceを開始しますか?

私のアプリには、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への単純な変換以外のコードです

BroadcastReceiverは、インテントクラスを自分の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);
15
blunden

どうすればこれを達成できますか?

BroadcastReceivergetBroadcast()PendingIntentを使用し、レシーバーがそのenqueueWork()メソッドからJobIntentServiceonReceive()メソッドを呼び出すようにします。私はこれを試していないことを認めますが、私の知る限り、うまくいくはずです。

24
CommonsWare