昨天聽到一個羣裏面的人說一些問題。大概提了一下熱啓動和冷啓動的方案,結果那小夥伴不知道。。。。
我這邊就簡單的說明一下:
熱啓動呢:就是你已經打開過APP但是實際上面你使用home鍵等。就是還存在後臺的應用。再次打開的時候算是屬於熱啓動了。
冷啓動呢:屬於你第一次打開APP,系統在給你開一個進程。
這個時候我在說明一下熱啓動的作用。我這邊公司想知道他APP開了幾次。而且需要準確的數據。這個時候,使用熱啓動。其實熱啓動很多地方都可以使用到。
現在貼一下代碼:(這個代碼是之前在百度上面copy過來的)首先我們要知道這個東西是不是還在前臺。
/**
* 程序是否在前臺運行
*
* @return
*/
public boolean isAppOnForeground() {
// Returns a list of application processes that are running on the
// device
ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
String packageName = getApplicationContext().getPackageName();
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
if (appProcesses == null)
return false;
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
// The name of the process that this object is associated with.
if (appProcess.processName.equals(packageName)
&& appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}
return false;
}
我也得知道這個APP什麼時候進去後臺,對吧~~那麼我們得知道安卓的Activity得生命週期。寫一個簡單版本得oncreate
onpause
onstop
ondestory
那麼這幾個裏面我應該選哪一個進行記錄呢oncreate和onDestory不可能,onpause和onstop倆個。一個是暫停,但是不代表進去了後臺頁面。但是對於onstop是有的
所以這邊的選擇是onstop
@Override
protected void onStop() {
super.onStop();
if (!isAppOnForeground()) {
//app 進入後臺
isLive = false;
//全局變量isActive = false 記錄當前已經進入後臺
}
}
那麼知道生命週期的應該知道那個onResume這個:
@Override
protected void onResume() {
super.onResume();
mCurContext = this;
if (!isLive) {
//app 從後臺喚醒,進入前臺
HttpTwo();
isLive = true;
}
}
那麼代碼如上了~~