簡體   English   中英

Android 7意圖附加功能缺失

[英]Android 7 intent extras missing

有沒有人知道Android 7.0(Nougat)與Android 6.0(Lollipop)相比如何處理意圖附加功能有什么變化?

長話短說:我的應用程序可以在4.1(16)到6.0(23)的所有版本上運行,但在android 7.0(24)上崩潰了!

該應用程序創建一個待定意圖,意圖是具有附加功能的自定義廣播接收器。 然而,在android 7上,廣播接收器接收的意圖中不存在任何附加內容。

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中從來就不是特別可靠,並且它在Android 7.0上的AlarmManager PendingIntentAlarmManager 其他進程可能需要在Intent填入值,這涉及到操作附加內容,並且除了您自己的進程外無法在任何進程中完成,因為沒有其他進程具有您的自定義Parcelable類。

這個SO答案有一個解決方法,以Parcelable自己轉換為/從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");
    }

}

它對我來說很好。 希望能幫助到你 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM