Check if Android app is in Background?
我已经做了很多搜索,但没有找到合适的答案。问题是这样的:
假设我启动了具有活动A,B,C的android项目,并且在按下"主页"按钮后整个应用程序进入后台时(无论活动如何),我都需要捕获事件。
当用户再次启动应用程序时,它会从android维护的Activity堆栈中恢复。我想捕获此事件,并向用户"您的应用程序现在处于活动状态"显示吐司。
在将一个屏幕切换到另一个屏幕时,此举杯表演不可见,只有当用户再次回到应用程序时,才应该是第一次可见。
经过几天的努力,我发现了一些东西。希望它会在某些情况下有用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /** * Checks if the application is being sent in the background (i.e behind * another application's Activity). * * @param context the context * @return <wyn>true</wyn> if another application will be above this one. */ public static boolean isApplicationSentToBackground(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; } |
要使其正常工作,您应该将此内容包含在AndroidManifest.xml
中
1 | <uses-permission android:name="android.permission.GET_TASKS" /> |
有关更多详细信息。参考:android:如何检查应用程序是否在后台运行
按下Home按钮后,活动中将调用onStop方法。因此,您可以在sharedpreferences中设置一个
1 2 3 4 5 6 7 8 9 10 | @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_HOME) { //set flag true in shared preferences } }); |
当应用再次激活时,将调用此方法。在那儿写你的吐司。
1 2 3 4 5 6 | @Override public void onResume() { super.onResume(); } |