2014-04-01 44 views
1

我正在通過此方法調用服務的廣播接收器。如何將數據從服務傳遞給BroadcastReceiver

Intent intent = new Intent(NotifyService.this, AlarmReciever.class); 
    intent.putExtra("TIME",ttime); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 34324243, intent, 0); 
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    alarmManager.set(AlarmManager.RTC_WAKEUP,timee,pendingIntent); 

在Broadcastreceiver頁面中,我通過此方法接收。

Bundle b = in.getExtras(); 
    date = b.getString("TIME"); 

問題是在BroadcastReceiver頁面我得到空值。 我的問題是: -

如何將數據從服務傳遞給broadcastreceiver?

回答

2

在您的主要活動啓動您的服務爲

i = new Intent(this, SimpleService.class); 
startService(i); 
registerReceiver(broadcastReceiver, new IntentFilter(SimpleService.BROADCAST_ACTION)); 

使用發送廣播,從服務類發送任何價值mainactiviy類作爲

intent.putExtra("textval", s); 
sendBroadcast(intent); 

,然後在您的主要活動類接收它作爲

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 

      //do your coding here using intent 
     } 

    }; 
+0

但我直接從服務調用它,而不是使用活動 – Ash

0

OK我承擔的 「TTIME」 是個包子DLE(從代碼你寫的似乎很有道理)

嘗試,並收到類似這樣的

Bundle b= in.getBundleExtra("TIME"); 

萬一「TTTIME」是其他格式的說一個字符串或INT你可以得到的數據

in.getStringExtra("TIME"); 

整數::

在Broadcastreceiverlike的的onReceive此

字符串數據從不同類型的意向210個

in.getIntExtra("TIME", -1) // -1 is default value which will be return incase no matching integer found with the key "TIME" in intent "in" 

更多的細節和如何獲得數據是指android documentation

0

你錯過了這樣做: -

Intent intent = new Intent(NotifyService.this, AlarmReciever.class); 
sendBroadcast(intent); 

可以調用的PendingIntent像這樣: -

PendingIntent operation = PendingIntent.getBroadcast(Service.this, 
      0, intent, 0); 
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 
      System.currentTimeMillis(),5* 60 * 1000, operation); 

如果您將任何時間數據傳遞給廣播級,那麼您可以在接收機類中接收該數據爲

String mTime = NotifyService.time; 

試試這個。告訴我也。

相關問題