android.os.BadParcelableException: ClassNotFoundException when unmarshalling:解决办法

例如在用AlarmManager的时候

 

复制代码
 1 AlarmManager alarmMgr = (AlarmManager) mContext

 2                 .getSystemService(Context.ALARM_SERVICE);

 3         Intent intent = new Intent(ALARM_ALERT);

 4        // intent.setExtrasClassLoader(DBTask.class.getClassLoader());

 5         Bundle mBundle=new Bundle(); 

 6         mBundle.putParcelable(AlarmMeReceiver.DB_TASK_KEY,task); 

 7         intent.putExtras(mBundle); 

 8         int id=Integer.valueOf(task.id);

 9         PendingIntent pendIntent = PendingIntent.getBroadcast(

10                 mContext.getApplicationContext(), id, intent,

11                 PendingIntent.FLAG_UPDATE_CURRENT);

12         long triggerAtTime = task.time;

13         alarmMgr.set(AlarmManager.RTC_WAKEUP , triggerAtTime, pendIntent);
复制代码

 通过第6行 intent传提一个Parcelable对象 (Parcelable里面没有问题)

android.os.BadParcelableException: ClassNotFoundException when unmarshalling错误可以加上

intent.setExtrasClassLoader(DBTask.class.getClassLoader());

 

原因是android.platform.frameworks.base/core/java/android/content/Intent.java

复制代码
5052             try {

5053                 Bundle newb = new Bundle(other.mExtras);

5054                 newb.putAll(mExtras);

5055                 mExtras = newb;

5056             } catch (RuntimeException e) {

5057                 // Modifying the extras can cause us to unparcel the contents

5058                 // of the bundle, and if we do this in the system process that

5059                 // may fail.  We really should handle this (i.e., the Bundle

5060                 // impl shouldn't be on top of a plain map), but for now just

5061                 // ignore it and keep the original contents. :(

5062                 Log.w("Intent", "Failure filling in extras", e);

5063             }
复制代码

 

 

 android 中自定义的对象序列化的问题有两个选择一个是Parcelable,另外一个是Serializable。

一 序列化原因:

1.永久性保存对象,保存对象的字节序列到本地文件中;
2.通过序列化对象在网络中传递对象;
3.通过序列化在进程间传递对象。 

二 至于选取哪种可参考下面的原则:

1.在使用内存的时候,Parcelable 类比Serializable性能高,所以推荐使用Parcelable类。
2.Serializable在序列化的时候会产生大量的临时变量,从而引起频繁的GC。
3.Parcelable不能使用在要将数据存储在磁盘上的情况,因为Parcelable不能很好的保证数据的持续性在外界有变化的情况下。尽管Serializable效率低点, 也不提倡用,但在这种情况下,还是建议你用Serializable 。

你可能感兴趣的:(android.os.BadParcelableException: ClassNotFoundException when unmarshalling:解决办法)