0

我有這個問題:我設置alarmManager意圖和pendingintent,如果滿足一些條件,在意圖中加入一些額外的東西。 的問題是,我的接收器不讀我的演員:我的接收器沒有收到意圖

集alarmManager在MainActivity:

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
    Intent i = new Intent(MainActivity.this, AlarmReceiver.class); 
    PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this , 0, i, PendingIntent.FLAG_ONE_SHOT); 

     // conditions 
        i.putExtra("type", 1); 
        i.putExtra("mealType", 2); 
        Log.d(TAG , "type: " + i.getExtras().getInt("type")); 
        Log.d(TAG , "mealtype: " + i.getExtras().getInt("mealType")); 
        calendar.set(calendar.HOUR_OF_DAY, 7); 
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi); 

而且在logcat中我可以看到:

D/MAIN: type: 1 
D/MAIN: mealtype: 2 

但在我的接收器:

public void onReceive(Context context, Intent intent) { 

    /** 
    * Receiver 
    */ 
    Log.d(TAG, "Allarme ricevuto dal receiver"); 

    int type = intent.getExtras().getInt("type"); 
    Log.d(TAG , "type: " + type); 
    Log.d(TAG , "mealtype: " + intent.getExtras().getInt("mealType")); 
    Log.d(TAG , "unExisted: " + intent.getExtras().getInt("unExisted")); 



    if(type == 0){ 
     Intent service = new Intent(context, AlarmService.class); 
     service.putExtra("type", type); 
     context.startService(service); 
    } 

    if(type == 1){ 
     int mealType = intent.getExtras().getInt("mealType"); 

     Intent service1 = new Intent(context, AlarmService.class); 
     service1.putExtra("type", type); 
     service1.putExtra("mealType", mealType); 
     context.startService(service1); 
    } 
} 

我看到這個:

D/ALARM RECEIVER: Allarme ricevuto dal receiver 
D/ALARM RECEIVER: type: 0 
D/ALARM RECEIVER: mealtype: 0 
D/ALARM RECEIVER: unExisted: 0 

我看到all'key爲0,並且看作0「unExistest」,我從不在意圖中插入此密鑰。爲什麼?

回答

1

在創建PendingIntent之前,您需要設置Intent附加值。

例子:

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
Intent i = new Intent(MainActivity.this, AlarmReceiver.class); 
i.putExtra("type", 1); 
i.putExtra("mealType", 2); 
PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this , 0, i, PendingIntent.FLAG_ONE_SHOT); 
calendar.set(calendar.HOUR_OF_DAY, 7); 
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi); 
+0

非常感謝你,我不相信這是這麼簡單。 – BeginnerNub