【问题标题】:Can't get extra values from Intent无法从 Intent 获得额外的值
【发布时间】:2013-06-26 06:33:31
【问题描述】:

我知道要输入值我可以intent.putExtra(key, value) 并检索值我们可以intent.getStringExtra(key) 但在下面的代码中它的行为不符合预期。检索值时,我得到NUllPointer, printLn needs a message

我设置值的代码:

public void SetAlarm(Context context, int seconds, String type) {
    CustomLog.logBlue(Thread.currentThread().getStackTrace(), "set alarm");

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    intent.putExtra(ONE_TIME, Boolean.FALSE); //ONE_TIME = "oneTime"
    intent.putExtra("c", "ayush");

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), seconds * 1000, pi);

    CustomNotification.generateNotification(1, context, "Tracking enabled");
}

我正在检索 BroadcaseReceiver 的 onReceive 中的值: [省略无关代码]

@Override
public void onReceive(Context context, Intent intent) {
     Bundle extras = intent.getExtras();
     Log.e("test", extras.getString("c"); <------ ERROR
     // also tried intent.getStringExtra("c");
}

【问题讨论】:

    标签: android android-intent android-pendingintent


    【解决方案1】:

    在调用PendingIntent.getBroadcast() 时使用标志FLAG_UPDATE_CURRENT。在您的代码中:

    PendingIntent pi = PendingIntent.getBroadcast(
                                     context, 0, intent, 
                                     PendingIntent.FLAG_UPDATE_CURRENT);
    

    【讨论】:

    • 我遇到的问题不是 getBroadcast 方法,而是 getActivity。设置 FLAG_UPDATE_CURRENT 为我解决了这个问题。也许您也可以按照建议使用 FLAG_CANCEL_CURRENT here
    【解决方案2】:

    这样试试就行了

    Intent intent = new Intent(CurrentActivity.this, AlarmManagerBroadcastReceiver.class);     
    intent.putExtra("c", "ayush");
    

    在接收器中

    intent.getStringExtra("c")
    

    【讨论】:

      【解决方案3】:

      检查您是否将 onReceive(...) 的正确意图作为第二个值。

      否则,不应该行

      Bundle extras = intent.getExtras();
      

      更像

      Bundle extras = getIntent().getExtras();
      

      ?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-17
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        相关资源
        最近更新 更多