0
當我嘗試使用LocalBroadcastManager
發送來自ScheduledExecutorService
的任何操作時,看起來真正的操作尚未發送(或尚未發送)。下面是代碼示例:從ScheduledExecutorService發送廣播
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 - 它的工作原理!
我猜測它不應該依賴於UI線程。無論如何,我已經檢查過,沒有任何幫助。 – Eugene