2015-01-13 120 views
0

收到PARAMS我寫的發送廣播消息活動相關的服務,但在活動我總是得到空的結果(broadcastMessage爲空)。請參閱下面的代碼。活動從服務

服務代碼

 Intent i = new Intent("MessageBroadcast"); 
     i.putExtra("HuaeState", 200); 
     sendBroadcast(i); 

活動代碼:當我在調試模式下面放一個分界線,我能看到價值broadcastMessage爲空

  public void onReceive(Context context, Intent intent) { 
       String broadcastMessage = intent.getExtras().getString("HuaeState"); 

     } 
+0

是我的解決方案制定出來的? –

+0

對不起您的解決方案沒有工作,我發現我在活動使用getInt()代替的getString()。不過,我還是謝謝你:) – hoangnh

回答

1

原因是要添加整數值意圖並獲得作爲字符串。

使用getint()

String broadcastMessage = String.valueOf(intent.getExtras().getInt("HuaeState")); 

String broadcastMessage = String.valueOf(intent.getIntExtra("HuaeState", -1)); // Where -1 is default value to indicate that there is something wrong while reading value from intent 
+0

工程。感謝您的解釋 – hoangnh

+0

您最歡迎:)。 congss –

1

修改你的代碼在服務這樣的:

Intent i = new Intent("MessageBroadcast"); 
    Bundle bundle=new Bundle(); 
    bundle.putInt("HuaeState", 200); 
    sendBroadcast(i); 

and Receiver Like:

public void onReceive(Context context, Intent intent) { 
       Bundle bundle = intent.getExtras(); 
       int value = bundle.getInt("HuaeState"); 

     } 

你做的錯誤是你的值設置爲意圖,並正從捆綁的價值。