我需要在我的活动和正在运行的 IntentService 之间进行双向通信。
场景是这样的:应用程序可以在运行时安排警报,启动一个从 Web 获取一些数据并处理它的 IntentService。IntentService 完成时可能出现三种情况:
应用处于焦点状态,这意味着当 IntentService 完成时,应用需要使用新数据刷新其视图。
应用程序关闭并在 IntentService 完成工作后打开,因此应用程序将可以访问处理后的数据
- 该应用程序在 IntentService 运行时打开,在这种情况下,我需要从活动中询问 IntentService 是否在后台执行某些操作。
对于 1. 我已经在我的活动中实现了一个 BroadcastReceiver,它注册到 LocalBroadcastManager。当 IntentService 完成工作时,发送一个广播并且活动做出反应。这工作正常
对于 2. 没有什么需要做的
对于 3. 我不知道该怎么办。到目前为止,我已经尝试过:
在活动中:
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(BROADCAST_SEND_TO_SERVICE));
在 IntentService 中
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。有什么建议或者更简单的方式让 Activity 询问 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);
}
在 Activity 中,在服务运行时重新启动应用程序:
Log(MyIntentService.isRunning.get());
//this returns always false, even if the intent service is running
在 AndroidManifest 上
<service
android:name=".services.MyIntentService"
android:exported="false" />