判斷Android程序是否在前臺運行的兩種方法
更新時間:2015年06月11日 11:06:39 投稿:junjie
這篇文章主要介紹了判斷Android程序是否在前臺運行的兩種方法,本文直接給出實現(xià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)文章
Android 媒體庫數(shù)據(jù)更新方法總結(jié)
這篇文章主要介紹了Android 媒體庫數(shù)據(jù)更新方法總結(jié)的相關(guān)資料,需要的朋友可以參考下2017-04-04Android 實現(xiàn)手機接通電話后振動提示的功能
本文主要介紹Android 實現(xiàn)手機接通電話后振動提示的功能,這里整理了詳細(xì)的相關(guān)資料,并附有示例代碼,有需要的朋友可以參考下2016-08-08Android瀑布流照片墻實現(xiàn) 體驗不規(guī)則排列的美感
這篇文章主要為大家詳細(xì)介紹了Android瀑布流照片墻實現(xiàn),體驗不規(guī)則排列的美感,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-10-10Android webview與js交換JSON對象數(shù)據(jù)示例
js主動調(diào)用android的對象方式,android也無法返回給js一個jsonobject,需要js做一下轉(zhuǎn)換,具體代碼如下,感興趣的朋友可以參考下哈2013-06-06Intent傳遞對象之Serializable和Parcelable的區(qū)別
Intent在不同的組件中傳遞對象數(shù)據(jù)的應(yīng)用非常普遍,大家都知道在intent傳遞對象的方法有兩種:1、實現(xiàn)Serializable接口、2、實現(xiàn)Parcelable接口,接下來通過本文給大家介紹Intent傳遞對象之Serializable和Parcelable的區(qū)別,感興趣的朋友一起學(xué)習(xí)吧2016-01-01Android如何判斷手機是否有錄音權(quán)限的工具類
這篇文章主要為大家詳細(xì)介紹了Android判斷手機是否有錄音的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06