在Android中利用Intent在各個組件間通訊。java
基本類型:
String byte short int long char boolean float double
String[] byte[] short[] int[] long[] char[] boolean[] float[] double[]
序列化:
Parcelable CharSequence Serializable
Parcelable[] CharSequence[]
複製代碼
intent.putCharSequenceArrayListExtra();android
intent.putIntegerArrayListExtra();面試
intent.putStringArrayListExtra();數據庫
intent.putParcelableArrayListExtra();json
intent.putExtras(); 傳遞一個bundle對象,全部數據都封裝在bundle中
數組
Intent intent = new Intent(AActivity.this, BActivity.class);
byte[] bytes = new byte[1024 * 1024];
intent.putExtra("key", bytes);
startActivity(intent);
複製代碼
Caused by: android.os.TransactionTooLargeException: data parcel size 1048956 bytes
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:615)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3070)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1518)
複製代碼
原理:學Android 這麼久,intent傳遞數據最大多少呢? bash
結論:說明Intent傳遞數據大小是有限制的;具體限制大小爲 ((1*1024*1024) - (4096 *2))
app
可採用EventBus
等相似方案傳遞數據;測試
可聲明靜態變量來進行數據傳遞;「效率高,耦合性高」ui
可將數據先持久化再還原,可利用SharedPreferences
或 存入數據庫
,sp相對簡單;「效率低」
//將對象轉換爲 json字符串,使用sp儲存
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(userEntity);
//經過json字符串取出 ,轉爲對象
Gson gson = new GsonBuilder().serializeNulls().create();
UserEntity loginUser = gson.fromJson(jsonEntity,UserEntity.class);
複製代碼
Intent傳值類型要求:
1)Intent 傳輸的數據,都存放在一個 Bundle 類型的對象 mExtras 中,Bundle 要求全部存儲的數據,都是可被序列化的。
2)爲何這裏的Bundle
要求傳遞的數據必須序列化?
由於 Activity
之間傳遞數據,首先要考慮跨進程的問題,而Android中又是經過 Binder
機制來解決跨進程通訊的問題。涉及到跨進程,對於複雜數據就要涉及到序列化和反序列化的過程,這就註定是一次值傳遞(深拷貝)的過程。
3)全部經過Bundle傳遞數據都須要序列化嗎?
不是,這裏的序列化只與Binder的跨進程通訊有關,其餘例如Fragment傳值用到的Bundle不須要序列化。
序列化說明:
在 Android 中,序列化數據須要實現Serializable
或者Parcelable
。對於基礎數據類型的包裝類,自己就是實現了Serializable,而咱們自定義的對象,按需實現這兩個序列化接口的其中一個便可。
因此這個問題用反證法也能夠解釋,若是是引用傳遞,那傳遞過去的只是對象的引用,指向了對象的存儲地址,就只至關於一個Int的大小,也就根本不會出現TransactionTooLargeException
異常。