【Android】如何知道某个Activity是否在前台?

转载自zrong's blog

有一个Android应用包含包含一个后台程序,该程序会定期连接服务器来实现自定义信息的推送。但是,当这个应用处于前台的时候,后台程序就没有必要连接服务器了。这样可以节省网络资源,也更省电。

用什么方法知道该应用是否处于前台呢?

网上搜到的方法大多数都是使用下面的代码:

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();

但是查阅 Android文档 后发现,google并不推荐使用这个方法:

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() ,它并不需要增加特殊的权限。

下面是范例代码:

/**
 * 返回当前的应用是否处于前台显示状态
 * @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;
}

有错误之处感谢指出

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,185评论 25 709
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,794评论 2 45
  • 学位英语怎么破,你们有招没????
    Js仙人掌阅读 1,355评论 0 0
  • 请善待喜欢你的人。 茫茫人海,每个人都可能认识成千上万的人,每个人身边都有若干人,没有谁是人见人爱、花见花开,能不...
    胡椒面儿阅读 1,814评论 0 0
  • 只恐夜深花睡去,故烧高烛照红妆。 这个周末,练习画一枝贴梗海棠。 下面发一发我练习的过程,还希望路过的大神们多多指...
    ___5E___阅读 6,086评论 43 92

友情链接更多精彩内容