官方文檔詳細介紹了cold start孕索, warm start 和 hot start 3種情況下app啟動優(yōu)化 下邊是文檔地址
https://developer.android.com/topic/performance/vitals/launch-time
一:首先解釋下這幾個啟動狀態(tài)的場景
1,cold start :應(yīng)用完全從頭啟動
2糖权,warm start:
1)用戶在主actiivty點擊了back鍵退出了應(yīng)用(沒有調(diào)用Precess单绑。kill(myPid))這時的app進程還活著嗦董,用戶此時又點擊了桌面的啟動圖標若治,app進程不需要重新啟動 但是actiivty需要重新創(chuàng)建
2)由于系統(tǒng)內(nèi)存緊張 app進程被殺了 但是系統(tǒng)的back stack還保留著活動 此時用戶啟動app?
3居兆,hot start:進程存在activity也沒有銷毀(按下home鍵)此時再回到app 還有情況就是系統(tǒng)內(nèi)存緊張調(diào)用了activity的onTrimMemory(), 然后activity需要重新創(chuàng)建view 并實現(xiàn)渲染繪制同時還需要實例化業(yè)務(wù)對象
二:為了達到優(yōu)化app啟動速度的目的覆山,我們需要理解一下app啟動的過程?
但是我現(xiàn)在描述的過程不像網(wǎng)上大家看到的深入到內(nèi)核和framework的源碼角度來敘述二是基本簡述一下啟動的流程順序
Cold start 發(fā)生在手機開機后第一次啟動app或者是殺掉app進程后再次啟動,這個期間如果處理不好會極大的影響app的啟動速度和體驗泥栖,因為這個階段系統(tǒng)和app加載初始化的資源比其他任何狀態(tài)下都更多也就意味著消耗更多時間簇宽。
在cold start最開始階段 系統(tǒng)有3個任務(wù) 1:加載和啟動app。2:啟動app后立即顯示一個空白的window窗口吧享。3:創(chuàng)建app進程
創(chuàng)建app進程階段 app進程會有以下幾個步驟 1:創(chuàng)建app對象(application)魏割。2:啟動主線程。3:創(chuàng)建主activity钢颂。4:inflate Views钞它。5:布局屏幕(status bar navigation bar 我們的contentView)。6:開始繪制殊鞭。一旦app進程完成了第一幀的繪制 系統(tǒng)進程會把繪制好的actiivty把之前空白的window替換掉遭垛,這時用戶就可以使用app進行交互了。
Figure 1 shows how the system and app processes hand off work between each other.
Figure 1.?A visual representation of the important parts of a cold application launch.
Performance issues can arise during creation of the app and creation of the activity.
性能問題會發(fā)生在app的create和actiivty的create階段 也就是application的onCreate()(如果我們重寫了這個方法的話)和activity的onCreate()
Activity creation activity的創(chuàng)建
app進程創(chuàng)建了我們的activity操灿,activity做了以下的一些操作
Initializes values.
Calls constructors.
Calls the callback method, such as?Activity.onCreate(), appropriate to the current lifecycle state of the activity.
Typically, the?onCreate()?method has the greatest impact on load time, because it performs the work with the highest overhead: loading and inflating views, and initializing the objects needed for the activity to run.最關(guān)鍵的是這句話 activity的onCreate()方法執(zhí)行了非常大的一些操作例如inflate Views 初始化activity里的對象锯仪,所以我們一定不要把業(yè)務(wù)邏輯放在這個生命周期進行。
怎么檢測app啟動各個階段的加載時間呢? 谷歌搞出了google concole
Android vitals 這是一個工具
Android vitals can help improve your app's performance by alerting you, via the?Play Console, when your app's startup times are excessive. Android vitals considers your app's startup times excessive when the app's:
Cold?startup takes 5 seconds or longer.
Warm?startup takes 2 seconds or longer.
Hot?startup takes 1.5 seconds or longer.
A?daily session?refers to a day in which your app was used.
Android vitals doesn't report data for?hot?startups. For information on how Google Play collects Android vitals data, see the?Play Console?documentation.
但是我們可以在logcat中查看log來分析app啟動所消耗的時間? 只需要連接上設(shè)備趾盐,logcat上輸入過濾字符串Displayed 然后啟動應(yīng)用就可以觀察到了 下邊是我的截圖
Displayed