我创建了一个服务,它从一个活动的onCreate开始,并停止在activity的onDestroy方法上.现在我必须从服务的方法中检查活动是否在前台/后台运行(对于某些情况,例如应用程序被强制关闭).我怎样才能做到这一点?
>我需要这样做因为我知道如果任何应用程序被强制关闭或任何类型的崩溃,无法保证调用活动的onDestroy方法.因此,我的活动启动时启动的服务不会在任何崩溃或任何强制关闭事件后停止.
>我看过this link可以检查前景活动.但我需要在任何状态(前景或后台)检查正在运行的活动
解决方法
最后更新
检查所有活动:
@Override protected void onStop() { super.onStop(); if (AppConstants.isAppSentToBackground(getApplicationContext())) { // Do what ever you want after app close simply Close session } }
检查我们的应用是否正在运行的方法:
public static boolean isAppSentToBackground(final Context context) { try { ActivityManager am = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); // The first in the list of RunningTasks is always the foreground // task. RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0); String foregroundTaskPackageName = foregroundTaskInfo.topActivity .getPackageName();// get the top fore ground activity PackageManager pm = context.getPackageManager(); PackageInfo foregroundAppPackageInfo = pm.getPackageInfo( foregroundTaskPackageName,0); String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo .loadLabel(pm).toString(); // Log.e("",foregroundTaskAppName +"----------"+ // foregroundTaskPackageName); if (!foregroundTaskAppName.equals("Your App name")) { return true; } } catch (Exception e) { Log.e("isAppSentToBackground","" + e); } return false; }
答案再次更新
将以下方法与您的包名一起使用.如果您的任何活动位于前台,它将返回true.
public boolean isForeground(String myPackage){ ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List< ActivityManager.RunningTaskInfo > runningTaskInfo = am.getRunningTasks(1); ComponentName componentInfo = runningTaskInfo.get(0).topActivity; if(componentInfo.getPackageName().equals(myPackage)) return true; return false; }
答案已更新
首先检查此链接Checking if an Android application is running in the background
http://developer.android.com/guide/topics/fundamentals.html#lcycles是android应用程序的生命周期的描述.
当活动进入后台时,会调用onPause()方法.因此,您可以在此方法中停用更新通知.
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; }
在清单中加入permisions
<uses-permission android:name="android.permission.GET_TASKS" />