intent.putExtra()在待处理的意图中不起作用

时间:2015-04-24 11:25:19

标签: android android-intent

我通过alarmreceiver从服务类传递一个待处理的意图。但是,在pendingIntent触发后,broadcastreceiver类没有接收到intent.putExtra()信息。这是我用于触发pendingIntent

的代码
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();
}

未显示正在从待处理意图接收的Toast中的 msg 信息。相反,会显示一个空白的吐司。

6 个答案:

答案 0 :(得分:37)

试试这个

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);

答案 1 :(得分:2)

请记住在PendingIntent构造函数中放置一个唯一的id,或者当您尝试获取putExtra值时,您可能会遇到一些奇怪的事情。

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

答案 2 :(得分:1)

您必须使用var userInput = 40; //This will be set to what the user has entered in the text box. if (userInput < 1000) //1000 will be set the the max value you will allow. { for (int i = 0; i <= userInput; i++) { Console.WriteLine(i); } } else { //Give User an Error } 并确保String不为null:

getStringExtra()

并在PendingIntent之前反转你的putExtras:

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

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

答案 3 :(得分:1)

这是因为您首先初始化Intent并添加到PendingIntent。之后,您将在意图中添加信息。您应该向intent添加信息,然后将此意图添加到PendingIntent。

答案 4 :(得分:0)

 final Intent my_intent = new Intent(this.context , Alarm_Receiver.class);

    //put in extra string into my intent
    //tell the clock that the user pressed the "alarm on button"
    my_intent.putExtra("extra" , 1);
    int state = my_intent.getExtras().getInt("extra");
    Log.i("extraa" , "the state in the main activity in alarm on Button is: " + state);

我遇到了同样的问题,我发现您应该先将putExtra放在Intent上

答案 5 :(得分:0)

就我而言,我缺少 PendingIntent.FLAG_UPDATE_CURRENT 作为标志。