1. 程式人生 > >Activity之間使用intent傳遞大量資料帶來問題總結

Activity之間使用intent傳遞大量資料帶來問題總結

Activity之間使用Parcel傳遞大量資料產生的問題。Activity之間通過intent傳遞大量資料,導致新Activity無法啟動。Activity之間資料傳遞方式總結參考 這 裡。比較常用的是直接利用intent傳遞,比如使用bundle,如下:
Intent intent =new Intent(ActivityA.this,ActivityB.class); 
Bundle bundle =new Bundle();
bundle.putParcelableArrayList("data", dataList);
intent.putExtras(bundle);
startActivity
(intent);
問題:當傳遞資料量過大,比如list的size過大,會導致B無法啟動。現象即啟動失敗,activityB的oncreate()都不會執行。分析:官方文件提到TransactionTooLargeException異常,“The Binder transaction failed because it was too large.”即傳輸資料過大異常。並且提到這樣一句話:“ objects stored in the Binder transaction buffe”,這表明實際上底層parcel物件在不同activity直接傳遞過程中儲存在一個叫做“Binder transaction buffe
”的地方,既然是緩衝區,肯定有大小限制。
官方文件還提到The Binder transaction buffer has a limited fixed size, currently 1Mb, which is shared by all transactions in progress for the process. Consequently this exception can be thrown when there are many transactions in progress even when most of the individual transactions are of moderate size.
即緩衝區最大1MB,並且這是該程序中所有正在進行中的傳輸物件所公用的。至於都有哪些傳輸物件、具體怎麼分配,這個還不太清楚。可以肯定的是Activity之間使用Parcel傳輸資料是有大小限制的。那麼在傳輸大小可能很大的情況下就要做點處理了。-------另外,1. 使用Serializable和parcel傳輸相同物件,都轉換為byte[]後,parcel大概是serializable的20倍了。2. 但是官方建議使用Parcel,原因是說速度是serializable的將近10倍。Serializable: it's error prone and horribly slow. So in general:stay away fromSerializableif possible.
Parcelable:If you want to pass complex user-defined objects,take a look at theParcelableinterface. It's harder to implement, but it has considerable speed gains compared toSerializable.
但是有時候出現該問題時居然不報錯(我遇到的就沒拋異常),甚至沒有特殊的log(adb logcat -v threadtime -s ActivityManager 、adb logcat -b events)並沒有像文章或者官方文件中提到的“throwing a (or just loggingE: !!! FAILED BINDER TRANSACTION !!!on pre 15 API levels)”比較奇葩!---------針對parcel傳遞資料大小限制,自個兒做了個簡單實驗:機型:Galaxy Nexus系統:4.1.2  sdk16過程:ActivityA,ActivityB,DataBean(每個物件大概200byte),A啟動B並使用Parcel物件傳遞list<dataBean>。當list大小為900個時,無法啟動B。即傳輸資料大概在200*900 < 200k所以按照官方解釋,對於具體某一次Activity間傳輸的限制大小是不確定的,依據使用環境而定。解決方法:一. 限制傳遞資料量1. 靜態static2. 單例3. Application4. 持久化參考: