我有一个服务,这个服务运行一个Thread来运行一个AsyncTask并重写onProgressUpdate方法。在这种方法中,我发送消息给我的本地广播接收器。Android:LocalBroadcastReceiver不起作用
Intent intent = new Intent("BookDownloadService");
// You can also include some extra data.
intent.putExtra("bookID", book.bookID);
intent.putExtra("maxValue", update[1]);
intent.putExtra("currentValue", update[0]);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
而在我的活动我想获得的数据。
LocalBroadcastManager.getInstance(context).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int bookId = intent.getIntExtra("bookID", 1);
int maxValue = intent.getIntExtra("maxValue", 10);
int currentValue = intent.getIntExtra("currentValue", 0);
boolean isFinish = intent.getBooleanExtra("isFinish", false);
Log.d("Receiver Buch " + bookId, currentValue + " von " + maxValue + " finish: " + isFinish);
}
}, new IntentFilter("BookDownloadService"));
但是什么也没有发生。没有日志消息或错误。
看到http://developer.android.com/reference/android/os/AsyncTask.html,节**线程规则** – pskink 2014-08-28 13:43:43
我的所有其他代码在里面工作。 – Phillipp 2014-08-28 13:48:49
将'AsyncTask'替换为'Thread'(或根据服务的性质使用'IntentService')。在这种情况下,您不需要'AsyncTask',因为'LocalBroadcastManager'已经在主应用程序线程上传递它的消息。只需从线程调用'sendBroadcast()'。除此之外,添加日志记录或断点以确保您上面列出的两个代码段实际上已经执行过。例如,只有在调用'publishProgress()'时,才会调用'AsyncTask'上的'onProgressUpdate()'。 – CommonsWare 2014-08-28 13:50:29