アクティビティと実行中の IntentService の間で双方向の通信が必要です。
シナリオは次のようなものです。アプリは実行時にアラームをスケジュールし、Web からデータを取得して処理する IntentService を開始できます。IntentService が終了する場合、次の 3 つの状況が考えられます。
アプリはフォーカスされています。つまり、IntentService が完了すると、アプリはビューを新しいデータで更新する必要があります。
アプリは閉じられ、IntentService が作業を終了した後に開かれるため、アプリは処理されたデータにアクセスできます。
- アプリは IntentService の実行中に開かれます。この場合、バックグラウンドで何かを実行しているかどうかをアクティビティから IntentService に問い合わせる方法が必要です。
1. LocalBroadcastManager に登録されるアクティビティに BroadcastReceiver を既に実装しています。IntentService が作業を終了すると、ブロードキャストを送信し、アクティビティが反応します。これはうまくいきます
2. 何もする必要はありません
3.どうしたらいいのかわからない。これまでのところ、私はこれを試しました:
活動中:
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_SEND_TO_SERVICE));
インテントサービスで
private LocalBroadcastManager localBroadcastManager;
private BroadcastReceiver broadcastReceiverService = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BROADCAST_SEND_TO_SERVICE)) {
//does not reach this place
//Send back a broadcast to activity telling that it is working
}
}
};
@Override
protected void onHandleIntent(Intent intent) {
localBroadcastManager = LocalBroadcastManager.getInstance(context);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BROADCAST_SEND_TO_SERVICE);
localBroadcastManager.registerReceiver(broadcastReceiverService, intentFilter);
.... //do things
}
私の実装の問題は、IntentService で BroadcastReceiver が onReceive を起動しないことです。アクティビティが IntentService に何をしているのかを尋ねるための提案やより簡単な方法はありますか?
LE: アトミックブール値を取得しようとしています。サービス中:
public static AtomicBoolean isRunning = new AtomicBoolean(false);
@Override
protected void onHandleIntent(Intent intent) {
isRunning.set(true);
// do work
// Thread.sleep(30000)
isRunning.set(false);
}
アクティビティで、サービスの実行中にアプリを再起動する:
Log(MyIntentService.isRunning.get());
//this returns always false, even if the intent service is running
Androidマニフェストの場合
<service
android:name=".services.MyIntentService"
android:exported="false" />