2014-08-28 11 views
1

我有一個服務,這個服務運行一個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")); 

但是什麼也沒有發生。沒有日誌消息或錯誤。

+0

看到http://developer.android.com/reference/android/os/AsyncTask.html,節**線程規則** – pskink 2014-08-28 13:43:43

+0

我的所有其他代碼在裏面工作。 – Phillipp 2014-08-28 13:48:49

+0

將'AsyncTask'替換爲'Thread'(或根據服務的性質使用'IntentService')。在這種情況下,您不需要'AsyncTask',因爲'LocalBroadcastManager'已經在主應用程序線程上傳遞它的消息。只需從線程調用'sendBroadcast()'。除此之外,添加日誌記錄或斷點以確保您上面列出的兩個代碼段實際上已經執行過。例如,只有在調用'publishProgress()'時,纔會調用'AsyncTask'上的'onProgressUpdate()'。 – CommonsWare 2014-08-28 13:50:29

回答

0

您需要註冊/註銷接收器...

(onPause) 
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); 

(onResume) 
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, <your intentFilter>); 
+0

看看我的代碼。我註冊它。 – Phillipp 2014-08-28 13:43:32

+0

我看不到那個。德哦,現在我知道了。 – 2014-08-28 13:44:13

+0

如果我需要從Application上下文執行此操作,該怎麼辦? – 2016-05-18 19:16:14