判断Android程序是否在前台运行的两种方法
短信预约 -IT技能 免费直播动态提醒
@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;
}
方法二:
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;
}
您可能感兴趣的文章:Android 判断程序在前台运行还是后台运行Android 判断某个服务(service)是否运行Android实现Service在前台运行服务Android 判断某个Activity 是否在前台运行的实例
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341