2015-04-24 51 views
13

我通過alarmreceiver,從服務類傳遞一個掛起的意圖。但是,在pendingIntent觸發後,broadcastreceiver類不會收到intent.putExtra()信息。這裏是我的燒製的PendingIntentintent.putExtra()在等待意圖不起作用

Intent aint = new Intent(getApplicationContext(), AlarmReceiver.class); 
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, aint, PendingIntent.FLAG_UPDATE_CURRENT); 
aint.putExtra("msg", msg); 
aint.putExtra("phone", phone); 
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent); 

代碼報警接收機類低於

public String msg, phonen; 

@Override 
public void onReceive(Context context, Intent intent){ 
    Bundle extras = intent.getExtras(); 
    msg = extras.getString("msg"); 
    phonen = extras.getString("phone"); 

    Log.d("onReceive", "About to execute MyTask"); 
    Toast.makeText(context,msg, Toast.LENGTH_LONG).show(); 
} 

在敬酒味精信息,正從待定的意圖收到的,不被顯示。相反,顯示一個空白的吐司。

回答

23

試試這個

Intent aint = new Intent(getApplicationContext(), AlarmReceiver.class); 
aint.putExtra("msg", msg); 
aint.putExtra("phone", phone); 



PendingIntent pendingIntent = PendingIntent.getBroadcast(
    getApplicationContext(), 
    id, 
    aint, 
    // as stated in the comments, this flag is important! 
    PendingIntent.FLAG_UPDATE_CURRENT); 
+4

對於那些希望在這個並有連接到的PendingIntent前.putExtra方法,該'PendingIntent.FLAG_UPDATE_CURRENT'是很重要的,所以嘗試上移動到另一個解決方案之前。 – DonutGaz

1

你必須使用getStringExtra(),並確保該字符串不是空:

 Intent intent = getIntent();  
    msg = intent.getStringExtra("msg"); 
    phonen = intent.getStringExtra("phone"); 

    if(msg!=null){ 
     Toast.makeText(context,msg, 
     Toast.LENGTH_LONG).show(); 
    } 

和的PendingIntent之前扭轉你的putExtras:

Intent aint = new Intent(getApplicationContext(), AlarmReceiver.class); 
    aint.putExtra("msg", msg); 
    aint.putExtra("phone", phone); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, aint, PendingIntent.FLAG_UPDATE_CURRENT); 
1

這是因爲你首先初始化Intent並添加到PendingIntent。之後,您正在添加信息的意圖。您應該向intent添加信息,然後將此意圖添加到PendingIntent。

0

請記住在PendingIntent構造函數中放入一個唯一的id,或者當您嘗試獲取putExtra值時可能會出現一些奇怪的現象。

PendingIntent pendingIntent = PendingIntent.getBroadcast(
      getApplicationContext(), 
      UUID.randomUUID().hashCode(), 
      aint, 
      PendingIntent.FLAG_UPDATE_CURRENT 
    );