Android – pending tent getbroadcast lost assignable data
That's the problem. My program runs perfectly in Android 6.0. After updating the device to Android 7.0, pendingtent can't pass assignable data to boracast revever. This is the code
sound the alarm
public static void setAlarm(@NonNull Context context, @NonNull Todo todo) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("KEY_TODO", todo);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, todo.remindDate.getTime(), alarmIntent);
}
Todo is a Parcelable class, and todo is the instance I need in the notification
In broadcast receiver, I can't get the available data
public void onReceive(Context context, Intent intent) {
Todo todo = intent.getParcelableExtra("KEY_TODO");
}
This is my intention when debugging. Enter image description here
I don't know why the intention is to include only one integer. Carcelable todo I've never put in. This code has no problem in Android 6.0, but it can't run in 7.0
resolvent:
Reference myself:
The most effective solution I know is to manually convert parseable to byte [] and put it into intent extra, and manually convert it back to parseable as needed. This stack overflow answer shows this technology, and this sample project provides a complete working sample
The key bit is the conversion between Parcelable and byte []:
/***
Copyright (c) 2016 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/
package com.commonsware.android.parcelable.marshall;
import android.os.Parcel;
import android.os.Parcelable;
// inspired by https://stackoverflow.com/a/18000094/115145
public class Parcelables {
public static byte[] toByteArray(Parcelable parcelable) {
Parcel parcel=Parcel.obtain();
parcelable.writeToParcel(parcel, 0);
byte[] result=parcel.marshall();
parcel.recycle();
return(result);
}
public static <T> T toParcelable(byte[] bytes,
Parcelable.Creator<T> creator) {
Parcel parcel=Parcel.obtain();
parcel.unmarshall(bytes, 0, bytes.length);
parcel.setDataPosition(0);
T result=creator.createFromParcel(parcel);
parcel.recycle();
return(result);
}
}