检测时,Android应用程序去backrgound [英] Detect when android app go backrgound

查看:114
本文介绍了检测时,Android应用程序去backrgound的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序需要检测是否我的应用程序将后台或切换到同一应用程序的另一项活动......我知道,我必须使用的onPause方法......但我怎么能区分两个例?

感谢您!

解决方案

 私有静态布尔isApplicationGoingToBackground(最终上下文的背景下){

        ActivityManager AM =(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        名单< RunningTaskInfo>任务= am.getRunningTasks(1);
        如果(!tasks.isEmpty()){
            组件名topActivity = tasks.get(0).topActivity;
            如果(!topActivity.getPackageName()。等于(context.getPackageName())){
                返回true;
            }
        }

        返回false;
    }
 

更新:getRunningTasks已声明不能保证是准确的。

呼叫的的onStop。的onStop被调用的任何接管屏幕ONSTART后 - 如果在同一个APK包的活动,然后你就不会进入后台。这确实需要GET_TASKS许可。

或绑定到服务ONSTART和放大器;取消绑定的onStop - 当你所有的活动都停止该服务将被onDestroyed(或轨道结合VS解除绑定,如果你不希望依靠onDestroyed获取调用 - 因为它可能不是。)

In my application I need to detect whether my application is going to background or is switching to another activity of the same application... I know that I have to use the onPause method... but how can I distinguish the two cases?

Thank you!

解决方案

private static boolean isApplicationGoingToBackground(final Context context) {

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }

        return false;
    }

UPDATE: getRunningTasks has been declared to not be guaranteed to be accurate.

Call in onStop. onStop gets called after onStart of whatever takes over the screen - if its an activity in the same apk package then you're not going into the background. This does require the GET_TASKS permission.

Or bind to a service onStart & unbind onStop - the service will then be onDestroyed when all your activities are stopped (or track binds vs unbinds if you don't want to rely on onDestroyed getting called - because it might not..).

这篇关于检测时,Android应用程序去backrgound的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆