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 。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM