例如在用AlarmManager的時候java
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
報android.os.BadParcelableException: ClassNotFoundException when unmarshalling錯誤能夠加上web
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。this
一 序列化緣由:spa
1.永久性保存對象,保存對象的字節序列到本地文件中;
2.經過序列化對象在網絡中傳遞對象;
3.經過序列化在進程間傳遞對象。
code
二 至於選取哪一種可參考下面的原則:orm
1.在使用內存的時候,Parcelable 類比Serializable性能高,因此推薦使用Parcelable類。
2.Serializable在序列化的時候會產生大量的臨時變量,從而引發頻繁的GC。
3.Parcelable不能使用在要將數據存儲在磁盤上的狀況,由於Parcelable不能很好的保證數據的持續性在外界有變化的狀況下。儘管Serializable效率低點, 也不提倡用,但在這種狀況下,仍是建議你用Serializable 。對象