当我尝试使用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秒后发送。{p}这是订阅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 - 它就可以了!
答案 0 :(得分:0)
由于您不在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();
}