判斷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 自定義view和屬性動畫實現(xiàn)充電進(jìn)度條效果
近期項目中需要使用到一種類似手機(jī)電池充電進(jìn)度的動畫效果,以前沒學(xué)屬性動畫的時候,是用圖片+定時器的方式來完成的,下面給大家分享android自定義view和屬性動畫實現(xiàn)充電進(jìn)度條2016-12-12
Android自定義FloatingActionButton滑動行為只隱藏不出現(xiàn)的問題小結(jié)
這篇文章主要介紹了Android自定義FloatingActionButton滑動行為只隱藏不出現(xiàn)的問題小結(jié),需要的朋友可以參考下2017-01-01
Android 自定義view實現(xiàn)水波紋動畫效果
這篇文章主要介紹了 Android 自定義view實現(xiàn)水波紋動畫效果的實例代碼,非常不錯,具有參考借鑒價值,需要的朋友參考下吧2017-01-01
Android 帶進(jìn)度條的WebView 示例代碼
本文主要介紹Android WebView,這里提供實例代碼,和效果圖供大家參考,希望能幫助有需要的小伙伴2016-07-07
Android Studio使用recyclerview實現(xiàn)展開和折疊功能(在之前的微信頁面基礎(chǔ)之上)
這篇文章主要介紹了Android Studio使用recyclerview實現(xiàn)展開和折疊(在之前的微信頁面基礎(chǔ)之上),本文通過截圖實例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2020-03-03

