判断Android程序是否在前台运行的两种方法
更新时间:2015年06月11日 11:06:39 投稿:junjie
这篇文章主要介绍了判断Android程序是否在前台运行的两种方法,本文直接给出实现代码,,需要的朋友可以参考下
@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; }
方法二:
/** * 需要权限: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; }
相关文章
Android webview与js交换JSON对象数据示例
js主动调用android的对象方式,android也无法返回给js一个jsonobject,需要js做一下转换,具体代码如下,感兴趣的朋友可以参考下哈2013-06-06Intent传递对象之Serializable和Parcelable的区别
Intent在不同的组件中传递对象数据的应用非常普遍,大家都知道在intent传递对象的方法有两种:1、实现Serializable接口、2、实现Parcelable接口,接下来通过本文给大家介绍Intent传递对象之Serializable和Parcelable的区别,感兴趣的朋友一起学习吧2016-01-01
最新评论