如何通过PendingIntent将自定义Serializable对象传递给BroadcastReceiver

我试图使用PendingIntent将自定义的Serialized对象从我的IntentService传递给BroadcastReceiver。

这是我的自定义对象:

Row.java

public class Row implements Serializable { private String name; private String address; public Row(BluetoothDevice device) { this.name = device.getName(); this.address = device.getAddress(); } } 

这是我的IntentService

MyIntentService.java

 public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @Override public void onCreate() { super.onCreate(); } @Override protected void onHandleIntent(Intent workIntent) { AlarmManager alarmMgr; PendingIntent alarmPendingIntent; Intent alarmIntent; // The object "RowsList" is passed from my MainActivity and is correctly received by my IntentService. // NO PROBLEMS HERE Row[] arrRows = (Row[])workIntent.getSerializableExtra("RowsList"); Log.i(TAG, "Inside Intent Service..."); int interval = 2; try{ if(interval != 0) { alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmIntent = new Intent(this, AlarmReceiver.class); alarmIntent.putExtra("IntentReason", "Reason"); // THIS GETS PASSED alarmIntent.putExtra("RowsList", arrRows); // THIS DOES NOT GET PASSED alarmPendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + (interval * 1000), alarmPendingIntent); } } catch (Exception ignored){} } } 

MainActivity.java

 // NO PROBLEMS HERE private Intent myIntent; myIntent = new Intent(getApplicationContext(), MyIntentService.class); Log.i(TAG, "Starting Intent Service..."); myIntent.putExtra("RowsList", arrRows); getApplicationContext().startService(intentListenBT); 

这是我的BroadcastReceiver:

AlarmReceiver.java

 public class AlarmReceiver extends BroadcastReceiver { Row[] arrRows; @Override public void onReceive(Context context, Intent intent) { this.context = context; String str = intent.getStringExtra("IntentReason"); // RECEIVED AS "Reason" arrRows = (Row[])intent.getSerializableExtra("RowsList"); // HERE IT IS null } } 

最令人讨厌的部分是此代码之前在我的Nexus 6P(Lollipop 6.0 API23)上运行。 一旦我将同一部手机更新到Android 7.0(Nougat),它就停止了工作。 牛轧糖中是否有任何改变导致了这个问题?

注意:

我使用带有API 23的Nexus 6P上的模拟器运行我的代码,它工作正常。

最有可能的是,您遇到了与自定义Parcelable实现相同的问题。 从博客文章中解释自己:基本上,如果核心操作系统进程需要修改Intent附加组件,那么该过程最终会尝试重新创建Serializable对象,作为设置附加组件以进行修改的一部分。 该进程没有您的类,因此它获得运行时exception。

最令人讨厌的部分是此代码之前在我的Nexus 6P(Lollipop 6.0 API23)上运行。

Android版本,您使用PendingIntent以及固件/ ROM可能会有所不同。 不要认为您当前的实现在任何Android版本上都是可靠的。

您唯一的选择是不将Serializable直接放入Intent extra中。 使用Serializable以外的东西(例如,嵌套的Bundle ),将Serializable转换为byte[]等。

此示例应用程序演示了后一种方法,应用于Parcelable对象。 相同的基本技术应该适用于Serializable 。 (给评论中的链接提示AyeVeeKay)。