2014-07-03 18 views
1

我有一個活動A和一個B類(擴展了BroadCastReceiver)。從A,我想提出警告這樣的:更改BroadcastReceiver中的另一個類

  Intent intent = new Intent(getApplicationContext(), TimerAlarmReceiver.class); 
      PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0); 
      alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 

      Calendar time = Calendar.getInstance(); 
      time.setTimeInMillis(System.currentTimeMillis()); 
      time.add(Calendar.SECOND, 5); 
      alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), 3000, pendingIntent); 

,和本B(名字是TimerAlarmReceiver):

public class TimerAlarmReceiver extends BroadcastReceiver { 
    public static long TIME; 
    public static Boolean TimerOn=false; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show(); 
     Log.v("Tag", Long.toString(TimeKeeper.Time)); 
    } 
    public static void setTime(long T) 
    {   TIME=TimerActivity.DMILLIS;   
    } 
} 

我想要做的就是訪問像從的onReceive一個靜態變量。我嘗試在活動中創建一個公共靜態成員。只要應用程序運行,日誌就會顯示正確的設置值。但是,如果我強制退出應用程序,onReceive中的日誌變爲0.

那麼如何將初始值傳遞給B?即使應用程序關閉也會保持該值(強制退出)。

回答

0

您可以將其作爲您用於創建PendingIntent的意圖的附加項之一傳遞。它將被傳送到您的BroadcastReceiver,您可以在那裏提取它。

另一種選擇是store it somewhere

+0

我試着把intent.put額外,但它似乎並沒有工作。你能把代碼給我嗎? –

+1

@harvey_slash檢查[此文章](http://stackoverflow.com/a/5256680/82788)。您可能需要爲額外工作指定一個操作。 – matiash