關於SharedPreference的commit和apply和ANR 原

看的SharedPreferencesImpl.java 辦法呢 有人是不用apply直接自己異步commit. 也有人用反射把那個QueuedWork的sFinishers變量弄成empty.

文檔上說的commit和apply, Unlike commit,which writes its preference out to persistent storage synchronously, apply commits its changes to the in-memory immediately but starts an asynchronous commit to disk,and you won't be notified of any failures. commit是有一個boolean返回值的,如果是true表示成功寫入persistent storage. 但是apply是沒有返回值的,你沒法知道它成功還是失敗.

爲什麼說異步執行的那些apply的任務的時間最終會嫁接到主線程上?

QueuedWork.waitToFinish()方法,會等着把這些Runnable都執行完.

QueuedWork的文檔裏有這麼一句話 This was created for writing SharedPreference edits out asynchronously so we'd have a mechanism to wait for the writes in Activity.onPause and similar places, but we may use this mechanism for other things in the future.

然後就猜是不是Activity的onPause()方法做了什麼處理 然後不是 然後再猜ActivityThread 就看到了

ActivityThread.java的多幾個地方比如handlePauseActivity()方法裏面就有一句 QueuedWork.waitToFinish(); 這裏是一定會等着那些異步的apply提交完才往後走的,所以可能ANR.

辦法呢 有人是不用apply直接自己異步commit. 也有人用反射把那個QueuedWork的sFinishers變量弄成empty.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章