關於Intent

是什麼?

在Android中利用Intent在各個組件間通訊。java

傳值方法:

  • intent.putExtra();
基本類型:
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傳遞 1M 的byte數組
Intent intent = new Intent(AActivity.this, BActivity.class);
byte[] bytes = new byte[1024 * 1024];
intent.putExtra("key", bytes);
startActivity(intent);
複製代碼
  • 結果:報異常 TransactionTooLargeException
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)
複製代碼

思考二:若是有限制,有什麼好的傳輸方案嗎?

  • 可採用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 使用 Bundle 存儲數據,究竟是值傳遞(深拷貝)仍是引用傳遞?

  • Intent傳值類型要求:

    1)Intent 傳輸的數據,都存放在一個 Bundle 類型的對象 mExtras 中,Bundle 要求全部存儲的數據,都是可被序列化的。

    2)爲何這裏的Bundle要求傳遞的數據必須序列化?

    由於 Activity 之間傳遞數據,首先要考慮跨進程的問題,而Android中又是經過 Binder機制來解決跨進程通訊的問題。涉及到跨進程,對於複雜數據就要涉及到序列化和反序列化的過程,這就註定是一次值傳遞(深拷貝)的過程。

    3)全部經過Bundle傳遞數據都須要序列化嗎?

    不是,這裏的序列化只與Binder的跨進程通訊有關,其餘例如Fragment傳值用到的Bundle不須要序列化。

  • 序列化說明:

    在 Android 中,序列化數據須要實現Serializable或者Parcelable。對於基礎數據類型的包裝類,自己就是實現了Serializable,而咱們自定義的對象,按需實現這兩個序列化接口的其中一個便可。

  • 因此這個問題用反證法也能夠解釋,若是是引用傳遞,那傳遞過去的只是對象的引用,指向了對象的存儲地址,就只至關於一個Int的大小,也就根本不會出現TransactionTooLargeException異常。

思考四:intent與bundle的序列化和反序列化規則?

思考五:序列化和反序列化的關鍵點是什麼?

感謝

面試常客:Intent 能傳遞多大 Size 的數據?| 付阿里的建議方案!

學Android 這麼久,intent傳遞數據最大多少呢?

intent傳遞數據太大,報TransactionTooLargeException異常

相關文章
相關標籤/搜索