[英]Detect when Android app is going to background
在我的应用程序中,我需要检测我的应用程序是进入后台还是切换到同一应用程序的另一个活动......我知道我必须使用 onPause 方法......但我如何区分这两种情况?
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.更新:已声明 getRunningTasks 不能保证准确。
Call in onStop.调用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. onStop 在 onStart 接管屏幕后被调用 - 如果它是同一个 apk 包中的活动,那么你不会进入后台。 This does require the GET_TASKS permission.这确实需要 GET_TASKS 权限。
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..).或者绑定到服务 onStart 和解除绑定 onStop - 当您的所有活动停止时,该服务将被 onDestroyed (或者如果您不想依赖 onDestroyed 被调用,则跟踪绑定与解除绑定 - 因为它可能不会......)。
There is no direct approach to get the app status while background or foreground, but even i have faced this issue, and found the solution with onWindowFocusChanged and onStop.没有直接的方法可以在后台或前台获取应用程序状态,但即使我也遇到过这个问题,并通过 onWindowFocusChanged 和 onStop 找到了解决方案。 For more details: http://vardhan-justlikethat.blogspot.in/2013/05/android-solution-to-detect-when-android.html更多详情: http : //vardhan-justlikethat.blogspot.in/2013/05/android-solution-to-detect-when-android.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.