如何知道某个ACTIVITY是否在前台?
2014-10-27 16:22
99 查看
本文链接:http://zengrong.net/post/1680.htm
有一个Android应用包含包含一个后台程序,该程序会定期连接服务器来实现自定义信息的推送。但是,当这个应用处于前台的时候,后台程序就没有必要连接服务器了。这样可以节省网络资源,也更省电。用什么方法知道该应用是否处于前台呢?
网上搜到的方法大多数都是使用下面的代码:
1 2 3 4 5 6 | ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); //获得task列表 List<ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1); Log.d("topActivity", "CURRENT Activity ::"+ taskInfo.get(0).topActivity.getClassName()); ComponentName componentInfo = taskInfo.get(0).topActivity; componentInfo.getPackageName(); |
This should never be used for core logic in an application, such as deciding between different behaviors based on the information found here. Such uses are not supported, and will likely break in the future. For example, if multiple applications can be actively running at the same time, assumptions made about the meaning of the data here for purposes of control flow will be incorrect.
而且,这个方法还要求设置
android.permission.GET_TASKS权限。
因此,我必须寻找更加合适的方法来做这件事。最终,我找到这个方法getRunningAppProcesses(),它并不需要增加特殊的权限。
下面是范例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /** * 返回当前的应用是否处于前台显示状态 * @param $packageName * @return */ private boolean isTopActivity(String $packageName) { //_context是一个保存的上下文 ActivityManager __am = (ActivityManager) _context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> __list = __am.getRunningAppProcesses(); if(__list.size() == 0) return false; for(ActivityManager.RunningAppProcessInfo __process:__list) { Log.d(getTAG(),Integer.toString(__process.importance)); Log.d(getTAG(),__process.processName); if(__process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && __process.processName.equals($packageName)) { return true; } } return false; } |
相关文章推荐
- 如何知道某个Activity是否在前台?
- 如何知道某个Activity是否在前台?
- ActivityLifecycleCallbacks如何判断APP是否在前台
- 如何判断Activity是否在前台显示
- 如何知道一个域名是否被注册过或被K过呢?
- 如何才能知道TCP网络端口是否打开?
- 教你如何知道MSN的好友是否删除了你
- 如何知道float和int的零在二进制上的表示是否相同
- 如何知道你的Linux系统机器是否被黑
- 高手们请问如何知道一个点是否在一个扇形内呢?
- 给出对方QQ号,如何知道对方是否在线 JS
- 如何知道你的电脑是否含有病毒
- 8.判断单链表是否有环?如何找到环的“起始”点?如何知道环的长度?
- android 如何判断程序是否在前台运行
- android 如何判断程序是否在前台运行
- 如何知道一个开发人员是否能融入团队?
- 如何知道网中IP是否占用
- 如何知道AppDomain租约是否已过期呢
- 如何知道 Internet Explorer 中是否启用了 ActiveX
- 如何知道自己的Windows是否已激活? 如何实现免激活升级? 重装Windows不需再激活?