[英]Sending broadcast from ScheduledExecutorService
當我嘗試使用LocalBroadcastManager
從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線程上,請嘗試以下操作:
public void run() { Looper.prepare(); sendAction(action); Looper.loop(); }
public void run()
{
new AsyncTask<Void, Void, Void>()
{
@Override
protected Void doInBackground(Void... params)
{
return null;
}
protected void onPostExecute(Void result)
{
sendAction(action);
}
}.execute();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.