判斷Android程序是否在前臺運(yùn)行的兩種方法
@Override
protected void onStop() {
if (!isAppOnForeground()) {
Debug.i("dwy", "enter background");
mIsBackground = true;
} else {
Debug.i("dwy", "foreground");
mIsBackground = false;
}
Judge is App in background when onStop() get called.
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;
}
方法二:
/**
* 需要權(quán)限:android.permission.GET_TASKS
*
* @param context
* @return
*/
public boolean isApplicationBroughtToBackground(Context context) {
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (tasks != null && !tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
Debug.i(TAG, "topActivity:" + topActivity.flattenToString());
Debug.f(TAG, "topActivity:" + topActivity.flattenToString());
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
相關(guān)文章
一文詳解無痕埋點(diǎn)在Android中的實(shí)現(xiàn)
很多時候因?yàn)楫a(chǎn)品都會要獲取用戶的行為,需要客戶端進(jìn)行相關(guān)的埋點(diǎn),下面這篇文章主要給大家介紹了關(guān)于無痕埋點(diǎn)在Android中實(shí)現(xiàn)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
Android 媒體庫數(shù)據(jù)更新方法總結(jié)
這篇文章主要介紹了Android 媒體庫數(shù)據(jù)更新方法總結(jié)的相關(guān)資料,需要的朋友可以參考下2017-04-04
Android 實(shí)現(xiàn)手機(jī)接通電話后振動提示的功能
本文主要介紹Android 實(shí)現(xiàn)手機(jī)接通電話后振動提示的功能,這里整理了詳細(xì)的相關(guān)資料,并附有示例代碼,有需要的朋友可以參考下2016-08-08
Android瀑布流照片墻實(shí)現(xiàn) 體驗(yàn)不規(guī)則排列的美感
這篇文章主要為大家詳細(xì)介紹了Android瀑布流照片墻實(shí)現(xiàn),體驗(yàn)不規(guī)則排列的美感,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10
Android自定義控件LinearLayout實(shí)例講解
這篇文章主要為大家詳細(xì)介紹了Android自定義控件LinearLayout實(shí)例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-05-05
Android webview與js交換JSON對象數(shù)據(jù)示例
js主動調(diào)用android的對象方式,android也無法返回給js一個jsonobject,需要js做一下轉(zhuǎn)換,具體代碼如下,感興趣的朋友可以參考下哈2013-06-06
Android側(cè)滑效果簡單實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了Android側(cè)滑效果簡單實(shí)現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11
Intent傳遞對象之Serializable和Parcelable的區(qū)別
Intent在不同的組件中傳遞對象數(shù)據(jù)的應(yīng)用非常普遍,大家都知道在intent傳遞對象的方法有兩種:1、實(shí)現(xiàn)Serializable接口、2、實(shí)現(xiàn)Parcelable接口,接下來通過本文給大家介紹Intent傳遞對象之Serializable和Parcelable的區(qū)別,感興趣的朋友一起學(xué)習(xí)吧2016-01-01
Android如何判斷手機(jī)是否有錄音權(quán)限的工具類
這篇文章主要為大家詳細(xì)介紹了Android判斷手機(jī)是否有錄音的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06

