Android 缺少 7 个额外的意图

Android 7 intent extras missing

有谁知道与 Android 6.0 (Lollipop) 相比,Android 7.0 (Nougat) 处理 intent extras 的方式是否有任何变化?

长话短说:我的应用程序在 4.1(16) 到 6.0(23) 的所有版本上都按预期运行,但在 android 7.0(24) 上崩溃了!

该应用创建了一个待处理的意图,该意图是针对具有附加功能的自定义广播接收器。然而,在 android 上,有 7 none 的额外内容存在于广播接收器接收到的意图中。

MainActivity.java

Intent intent = new Intent(context, PollServerReceiver.class);

// TODO:  Remove after DEBUGGING is completed!
intent.putExtra("TESTING1", "testing1");
intent.putExtra("TESTING2", "testing2");
intent.putExtra("TESTING3", "testing3");

 // PendingIntent to be triggered when the alarm goes off.
 final PendingIntent pIntent = PendingIntent.getBroadcast(context,
            PollServerReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Setup alarm to schedule our service runs.
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, firstRun, freqMilis, pIntent);

PollServerReceiver.java

Bundle extras = intent.getExtras();
Log.d(TAG, "onReceive: TESTING1 = " + extras.getString("TESTING1")); // null here

// None of the three "TESTING*" keys are there!
for (String key : extras.keySet()) {
    Object value = extras.get(key);
    Log.d(TAG, String.format("onReceive extra keys: %s %s (%s)", key, value.toString(), value.getClass().getName()));
}

堆栈跟踪显然给出了 NullPointerException 作为崩溃的原因。 如果它会在所有版本中崩溃也不会那么奇怪,但在这种情况下它只是最新的 android。有人有什么想法吗?

注意:我已经尝试使用不同的标志创建待定意图,包括(0PendingIntent.FLAG_UPDATE_CURRENTPendingIntent.FLAG_CANCEL_CURRENT)仍然得到完全相同的结果。

将自定义 Parcelable 放在 PendingIntent 中从来都不是特别可靠,而且 it flat-out will not work in an AlarmManager PendingIntent on Android 7.0。其他进程可能需要将值填充到 Intent 中,这涉及到操作额外的部分,这不能在任何进程中完成,但你自己的,因为没有其他进程有你的自定义 Parcelable class.

This SO answer 有一个解决方法,其形式是将 Parcelable 自己 to/from 转换为 byte[].

我遇到了类似的问题,但我想我找到了一个简单的解决方案。将您的数据放入一个 Bundle 中,并根据您的意图发送该 Bundle。在我的例子中,我想按照我的意图发送一个可序列化的对象。

设置闹钟:

AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReciever.class);
Bundle bundle = new Bundle();

//creating an example object
ExampleClass exampleObject = new ExampleClass();

//put the object inside the Bundle
bundle.putSerializable("example", exampleObject);

//put the Bundle inside the intent
intent.putExtra("bundle",bundle);

PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

//setup the alarm
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);

收到报警:

public class AlarmReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // get the Bundle
        Bundle bundle = intent.getBundleExtra("bundle");
        // get the object
        ExampleClass exampleObject = (ExampleClass)bundle.getSerializable("example");
    }

}

对我来说效果很好。希望对您有所帮助:)