0

在我的實驗室工作,我要創建一個服務,該服務發送通知時,電池放電的速度大於設定。的Android:如何從業務數據傳遞到廣播reciever

我創建的活動與的EditText此值和用於啓動和停止的服務2按鈕。我還創建了一個BatteryService類,繼承自Service類和BatteryReciever。

現在reciver寄存器與服務行動BATTERY_CHANGED在onStartCommand。問題是如何將數據傳遞給接收者或如何知道服務中的事件。

什麼是解決這一任務的最佳方法是什麼?

回答

0

要觸發BroadcastReceiver,你需要使用

sendBroadcast(intent); 

把你想從Serviceintent發送如下數據:在onReceive()

Intent intent = new Intent("my.custom.action"); 
Bundle b = new Bundle(); 
b.putSerializable("name", name); 
b.putShort("count", count); 
intent.putExtra("bundle", b); 
sendBroadcast(intent); 

和檢索數據該BroadcastReceiver的方法:

@Override 
public void onReceive (Context context, Intent intent){ 
    Bundle b = intent.getExtras(); 
    // do awesome things ... 
} 

試試這個。這將工作。

+0

如果我sendBroadcast,它會調用reciever的另一個實例。調用後,我將失去它 – hinduCoder 2015-04-04 14:00:27

+0

沒有「接收器的另一個實例」。 '意圖'激活當前註冊的接收器。 – 2015-04-04 14:01:39

+0

我收到了預期的效果,但是我創建了自定義操作的意圖(並且收件人也使用了它)。正如我所說的那樣,這是明確的意圖。謝謝你,對我很有幫助 – hinduCoder 2015-04-04 14:26:48

相關問題