2016-05-29 17 views
-1

我一直停留3天,現在運行在同一播出多個實例,無論是什麼,我想要做的是非常基本的或令人難以置信的複雜becasue我似乎無法在任何地方找到答案。我有一個BroadcastReceiver和一個按鈕,發送意圖開始廣播,每次我點擊按鈕它發送不同的數據(int ++),意圖有一個10米的計時器,所以我有兩個問題:如何同時有

1 :要送我必須使用sendBroadcast(intent),但設置定時器我必須使用AlarmManager,只是將數據放入意圖和意圖進入AlarmManager使得它總是發送插入第一個數據,如何進行數據我解決這個問題?

2:我想有同一個BroadcastReceiver的多個實例同時計數而不會相互干擾。情況舉例:用戶創建1個鬧鐘,5m後他創建另一個鬧鐘,發生了什麼事情只有一個鬧鐘在設置第二個鬧鐘10m後執行,覆蓋第一個鬧鐘,預期結果是在設置10m後執行第一個鬧鐘第一個,在第二個之後執行第二個,我該如何實現?

我的廣播接收器:

public class Broadcast_RemoveClass extends BroadcastReceiver { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      int i = intent.getExtras().getInt("mInt"); 
      Toast.makeText(context, "done"+i, Toast.LENGTH_LONG).show(); 
     } 
    } 

發送內部的onClick意圖:

public void startAlert(int i) { 
    Intent intent = new Intent(getActivity(), Broadcast_RemoveClass.class); 
    Bundle bd = new Bundle(); 
    bd.putInt("mInt", i); 
    intent.putExtras(bd); 
    // getActivity().sendBroadcast(intent); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 0, intent, 0); 
    AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE); 
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000 * 60 * 10, pendingIntent); 
    Toast.makeText(getActivity(), "countdown started " ,Toast.LENGTH_SHORT).show(); 
} 

傢伙請幫助,哪怕它只是其中一個問題

回答

1

當你做:

PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity().getApplicationContext(), 0, intent, 0); 

第一0充當用於此待處理意圖的ID。這樣您可以取消它或將來更新它。如果您向系統發送具有相同標識(以及相應標誌)的另一個掛起的意圖,它將替換之前的意向。因此,使用不同的ID發佈您的新掛起的意圖。您可以使用硬編碼0所有情況下....

這種行爲也被認爲是在end.You設置已將該值設置爲0的標誌控制。這是毫無意義的...有沒有公共靜態PendingIntent類中的最終字段爲0值。切勿將硬編碼值用於標誌。即使他們有一個有效的值,他們也會讓你的代碼非常混亂。取決於你想做什麼,用適當的標誌替換最後的0。 PendingIntent類中的可用標誌爲:

int FLAG_CANCEL_CURRENT 
Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one. 
int FLAG_IMMUTABLE 
Flag indicating that the created PendingIntent should be immutable. 
int FLAG_NO_CREATE 
Flag indicating that if the described PendingIntent does not already exist, then simply return null instead of creating it. 
int FLAG_ONE_SHOT 
Flag indicating that this PendingIntent can be used only once. 
int FLAG_UPDATE_CURRENT 
Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent. 

您不需要第二個廣播接收器實例。同一個廣播接收機可以處理你想要的所有意圖。

+0

太感謝你了,這正是我一直在尋找! –

+0

歡迎您......當答案滿足您的問題時,您將其標記爲已接受,請點擊複選框...不會高舉它。 – Anonymous

+0

是的,我知道這種做法,我決定不因爲其他的問題仍然沒有答案 –