当我尝试通过ScheduledExecutorService
使用发送任何操作时LocalBroadcastManager
,似乎尚未发送实际操作(或尚未交付)。这是代码示例:
public class SomeService extends IntentService {
private static final String TAG = SomeService.class.getSimpleName();
public static final String ACTION = "some-action";
private ScheduledExecutorService scheduledTaskExecutor = Executors.newScheduledThreadPool(1);
public SomeService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (action.equals("scheduled_action")) {
scheduledTaskExecutor.schedule(new ScheduledAction(ACTION), 10, SECONDS);
} else if (action.equals("send_it_now")) {
sendAction(ACTION);
}
}
private void sendAction(String action) {
Log.d(TAG, "send action [" + action + "]");
Intent intent = new Intent(action);
LocalBroadcastManager.getInstance(SomeService.this).sendBroadcast(intent);
}
// it also could be Callable, but effect is pretty the same
private class ScheduledAction implements Runnable {
final String action;
ScheduledAction(String action) {
this.action = action;
}
@Override
public void run() {
sendAction(action);
}
}
}
根据传入的操作,服务ACTION
会立即发送或在 10 秒后发送。这是订阅的活动ACTION
:
public class SomeActivity extends Activity {
private static final String TAG = SomeActivity.class.getName();
private BroadcastReceiver actionReceiver = new ActionReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction(SomeService.ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(actionReceiver, filter);
}
@Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(actionReceiver);
super.onDestroy();
}
private class ActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "received action [" + action + "]");
}
}
}
如果send_it_now
一切都按预期工作:
Intent intent = new Intent(..., SomeService.class);
intent.setAction("send_it_now");
startService(intent);
我看到打印到 logcat 的适当消息:
...
SomeService send action [some-action]
SomeActivity received action [some-action]
...
但是当我尝试使用时scheduled_action
:
Intent intent = new Intent(..., SomeService.class);
intent.setAction("scheduled_action");
startService(intent);
我看到动作已发送,但未在活动中收到:
...
SomeService send action [some-action]
...
那么,任何人都可以解释这段代码有什么问题,或者至少说明我可以找到解释的方向吗?
一些更新。如果我将Timer和TimerTask用于相同的目的,我会使用ScheduledExecutorService和ScheduledFuture - 它可以工作!