一個Intent與LinkedHashMap的小問題

前言

這周QA報了一個小bug,頁面A傳給頁面B的數據順序不對,查了一下代碼,原來頁面A中數據存儲容器用的是HashMap,而HasMap存取是無序的,因此傳給B去讀數據的時候,天然順序不對。數組

解決

既然HashMap是無序的,那我直接用LinkedHashMap來代替不就好了,大多數人估計看到這個bug時,開始都是這麼想的。因而我就順手在HashMap前加了一個Linked,點了一下run,泯上一口茶,靜靜等待着奇蹟的發生。bash

然而奇蹟沒有來臨,奇怪的事反卻是發生了,B頁面收到數據後,竟然報了一個類型強轉錯誤,B收到的是HashMap,而不是LinkedHashMap,怎麼可能!!!!我趕忙放下茶杯,review了一下代碼,沒錯啊,A頁面傳遞的確實是LinkedHashMap,可是B拿到就是HashMap,真是活見鬼了。app

我立馬Google了一下,遇到這個錯誤的人還真很多,評論區給出的一種解決方案就是用Gson將LinkedHashMap序列化成String,再進行傳遞。。。因爲bug催的緊,我也沒有去嘗試這種方法了,直接就放棄了傳遞Map,改用ArrayList了。不事後來看源碼,又發現了另一種方式,稍後再說。ide

緣由

Bug卻是解決了,可是Intent沒法傳遞LinkedHashMap的問題還在我腦海裏縈繞,我就稍微翻看了一下源碼,恍然大悟!ui

HashMap實現了Serializable接口,而LinkedHashMap是繼承自HashMap的,因此用Intent傳遞是沒有問題的,咱們先來追一下A頁面傳遞的地方:this

intent.putExtra("map",new LinkedHashMap<>());複製代碼

接着往裏看:spa

public Intent putExtra(String name, Serializable value) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putSerializable(name, value);
    return this;
}複製代碼

intent是直接構造了一個Bundle,將數據傳遞到Bundle裏,Bundle.putSerializable()裏其實也是直接調用了父類BaseBundle.putSerializable():代理

void putSerializable(@Nullable String key, @Nullable Serializable value) {
    unparcel();
    mMap.put(key, value);
}複製代碼

這裏直接將value放入了一個ArrayMap中,並無作什麼特殊處理。code

事情到這彷佛沒有了下文,那麼這個LinkedHashMap又是什麼時候轉爲HashMap的呢?有沒有多是在startActivity()中作的處理呢?orm

瞭解activity啓動流程的工程師應該清楚,startActivity()最後調的是:

ActivityManagerNative.getDefault().startActivity()複製代碼

ActivityManagerNative是個Binder對象,其功能實現是在ActivityManagerService中,而其在app進程中的代理對象則爲ActivityManagerProxy。因此上面的startActivity()最後調用的是ActivityManagerProxy.startActivity(),咱們來看看這個方法的源碼:

public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
        String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    ......
    intent.writeToParcel(data, 0);
    ......
    int result = reply.readInt();
    reply.recycle();
    data.recycle();
    return result;
}複製代碼

注意到方法中調用了intent.writeToParcel(data, 0),難道這裏作了什麼特殊處理?

public void writeToParcel(Parcel out, int flags) {
    out.writeString(mAction);
    Uri.writeToParcel(out, mData);
    out.writeString(mType);
    out.writeInt(mFlags);
    out.writeString(mPackage);
    ......
    out.writeBundle(mExtras);
}複製代碼

最後一行調用了Parcel.writeBundle()方法,傳參爲mExtras,而以前的LinkedHashMap就放在這mExtras中。

public final void writeBundle(Bundle val) {
    if (val == null) {
        writeInt(-1);
        return;
    }

    val.writeToParcel(this, 0);
}複製代碼

這裏最後調用了Bundle.writeToParcel(),最終會調用到其父類BaseBundle的writeToParcelInner():

void writeToParcelInner(Parcel parcel, int flags) {
    // Keep implementation in sync with writeToParcel() in
    // frameworks/native/libs/binder/PersistableBundle.cpp.
    final Parcel parcelledData;
    synchronized (this) {
        parcelledData = mParcelledData;
    }
    if (parcelledData != null) {
       ......
    } else {
        // Special case for empty bundles.
        if (mMap == null || mMap.size() <= 0) {
            parcel.writeInt(0);
            return;
        }
        ......
        parcel.writeArrayMapInternal(mMap);
        ......
    }
}複製代碼

可見最後else分支裏,會調用Parcel.writeArrayMapInternal(mMap),這個mMap即爲Bundle中存儲K-V的ArrayMap,看看這裏有沒有對mMap作特殊處理:

void writeArrayMapInternal(ArrayMap<String, Object> val) {
    if (val == null) {
        writeInt(-1);
        return;
    }
    // Keep the format of this Parcel in sync with writeToParcelInner() in
    // frameworks/native/libs/binder/PersistableBundle.cpp.
    final int N = val.size();
    writeInt(N);
    if (DEBUG_ARRAY_MAP) {
        RuntimeException here =  new RuntimeException("here");
        here.fillInStackTrace();
        Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
    }
    int startPos;
    for (int i=0; i<N; i++) {
        if (DEBUG_ARRAY_MAP) startPos = dataPosition();
        writeString(val.keyAt(i));
        writeValue(val.valueAt(i));
        if (DEBUG_ARRAY_MAP) Log.d(TAG, " Write #" + i + " "
                + (dataPosition()-startPos) + " bytes: key=0x"
                + Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0)
                + " " + val.keyAt(i));
    }
}複製代碼

在最後的for循環中,會遍歷mMap中全部的K-V對,先調用writeString()寫入Key,再調用writeValue()來寫入Value。真相就在writeValue()裏:

public final void writeValue(Object v) {
    if (v == null) {
        writeInt(VAL_NULL);
    } else if (v instanceof String) {
        writeInt(VAL_STRING);
        writeString((String) v);
    } else if (v instanceof Integer) {
        writeInt(VAL_INTEGER);
        writeInt((Integer) v);
    } else if (v instanceof Map) {
        writeInt(VAL_MAP);
        writeMap((Map) v);
    } 
    ......
    ......
}複製代碼

這裏會判斷value的具體類型,若是是Map類型,會先寫入一個VAL_MAP的類型常量,緊接着調用writeMap()寫入value。writeMap()最後走到了writeMapInternal():

void writeMapInternal(Map<String,Object> val) {
    if (val == null) {
        writeInt(-1);
        return;
    }
    Set<Map.Entry<String,Object>> entries = val.entrySet();
    writeInt(entries.size());
    for (Map.Entry<String,Object> e : entries) {
        writeValue(e.getKey());
        writeValue(e.getValue());
    }
}複製代碼

可見,這裏並無直接將LinkedHashMap序列化,而是遍歷其中全部K-V,依次寫入每一個Key和Value,因此LinkedHashMap到這時就已經失去意義了。

那麼B頁面在讀取這個LinkedHashMap的時候,是什麼狀況呢?從Intent中讀取數據時,最終會走到getSerializable():

Serializable getSerializable(@Nullable String key) {
    unparcel();
    Object o = mMap.get(key);
    if (o == null) {
        return null;
    }
    try {
        return (Serializable) o;
    } catch (ClassCastException e) {
        typeWarning(key, o, "Serializable", e);
        return null;
    }
}複製代碼

這裏乍一看就是直接從mMap中經過key取到value,其實重要的邏輯全都在第一句unparcel()中:

synchronized void unparcel() {
    synchronized (this) {
        final Parcel parcelledData = mParcelledData;
        if (parcelledData == null) {
            if (DEBUG) Log.d(TAG, "unparcel "
                    + Integer.toHexString(System.identityHashCode(this))
                    + ": no parcelled data");
            return;
        }

        if (LOG_DEFUSABLE && sShouldDefuse && (mFlags & FLAG_DEFUSABLE) == 0) {
            Slog.wtf(TAG, "Attempting to unparcel a Bundle while in transit; this may "
                    + "clobber all data inside!", new Throwable());
        }

        if (isEmptyParcel()) {
            if (DEBUG) Log.d(TAG, "unparcel "
                    + Integer.toHexString(System.identityHashCode(this)) + ": empty");
            if (mMap == null) {
                mMap = new ArrayMap<>(1);
            } else {
                mMap.erase();
            }
            mParcelledData = null;
            return;
        }

        int N = parcelledData.readInt();
        if (DEBUG) Log.d(TAG, "unparcel " + Integer.toHexString(System.identityHashCode(this))
                + ": reading " + N + " maps");
        if (N < 0) {
            return;
        }
        ArrayMap<String, Object> map = mMap;
        if (map == null) {
            map = new ArrayMap<>(N);
        } else {
            map.erase();
            map.ensureCapacity(N);
        }
        try {
            parcelledData.readArrayMapInternal(map, N, mClassLoader);
        } catch (BadParcelableException e) {
            if (sShouldDefuse) {
                Log.w(TAG, "Failed to parse Bundle, but defusing quietly", e);
                map.erase();
            } else {
                throw e;
            }
        } finally {
            mMap = map;
            parcelledData.recycle();
            mParcelledData = null;
        }
        if (DEBUG) Log.d(TAG, "unparcel " + Integer.toHexString(System.identityHashCode(this))
                + " final map: " + mMap);
    }複製代碼

這裏主要是讀取數據,而後填充到mMap中,其中關鍵點在於parcelledData.readArrayMapInternal(map, N, mClassLoader):

void readArrayMapInternal(ArrayMap outVal, int N,
    ClassLoader loader) {
    if (DEBUG_ARRAY_MAP) {
        RuntimeException here =  new RuntimeException("here");
        here.fillInStackTrace();
        Log.d(TAG, "Reading " + N + " ArrayMap entries", here);
    }
    int startPos;
    while (N > 0) {
        if (DEBUG_ARRAY_MAP) startPos = dataPosition();
        String key = readString();
        Object value = readValue(loader);
        if (DEBUG_ARRAY_MAP) Log.d(TAG, " Read #" + (N-1) + " "
                + (dataPosition()-startPos) + " bytes: key=0x"
                + Integer.toHexString((key != null ? key.hashCode() : 0)) + " " + key);
        outVal.append(key, value);
        N--;
    }
    outVal.validate();
}複製代碼

這裏其實對應於以前所說的writeArrayMapInternal(),先調用readString讀出Key值,再調用readValue()讀取value值,因此重點仍是在於readValue():

public final Object readValue(ClassLoader loader) {
    int type = readInt();

    switch (type) {
    case VAL_NULL:
        return null;

    case VAL_STRING:
        return readString();

    case VAL_INTEGER:
        return readInt();

    case VAL_MAP:
        return readHashMap(loader);

    ......
    }
}複製代碼

這裏對應以前的writeValue(),先讀取之間寫入的類型常量值,若是是VAL_MAP,就調用readHashMap():

public final HashMap readHashMap(ClassLoader loader){
    int N = readInt();
    if (N < 0) {
        return null;
    }
    HashMap m = new HashMap(N);
    readMapInternal(m, N, loader);
    return m;
}複製代碼

真相大白了,readHashMap()中直接new了一個HashMap,再依次讀取以前寫入的K-V值,填充到HashMap中,因此B頁面拿到就是這個HashMap,而拿不到LinkedHashMap了。

一題多解

雖然不能直接傳LinkedHashMap,不過能夠經過另外一種方式來傳遞,那就是傳遞一個實現了Serializable接口的類對象,將LinkedHashMap做爲一個成員變量放入該對象中,再進行傳遞。如:

public class MapWrapper implements Serializable {

  private HashMap mMap;

  public void setMap(HashMap map){
      mMap=map;
  }

  public HashMap getMap() {
      return mMap;
  }
}複製代碼

那麼爲何這樣傳遞就好了呢?其實也很簡單,由於在writeValue()時,若是寫入的是Serializable對象,那麼就會調用writeSerializable():

public final void writeSerializable(Serializable s) {
    if (s == null) {
        writeString(null);
        return;
    }
    String name = s.getClass().getName();
    writeString(name);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(s);
        oos.close();

        writeByteArray(baos.toByteArray());
    } catch (IOException ioe) {
        throw new RuntimeException("Parcelable encountered " +
            "IOException writing serializable object (name = " + name +
            ")", ioe);
    }
}複製代碼

可見這裏直接將這個對象給序列化成字節數組了,並不會由於裏面包含一個Map對象而再走入writeMap(),因此LinkedHashMap得以被保存了。

結論:

一句話,遇到問題就多看源碼!

相關文章
相關標籤/搜索