检测Android应用何时进入后台 [英] Detect when Android app is going to background

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

问题描述

在我的应用程序中,我需要检测我的应用程序是要在后台运行还是要切换到同一应用程序的另一个活动...我知道我必须使用onPause方法...但是如何区分两者例?

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?

推荐答案

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;
    }

更新:已声明不保证getRunningTasks的准确性.

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

致电onStop.onStop在任何接管屏幕的onStart之后被调用-如果它是同一个apk包中的活动,则您不会进入后台.这确实需要GET_TASKS权限.

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.

或在Start&上绑定到服务取消onStop的绑定-当您停止所有活动时,该服务将被onDestroyed(或者,如果您不想依赖onDestroyed被调用,则跟踪绑定或取消绑定-因为它可能不会..).

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应用何时进入后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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