0

我有一个广播接收器,它启动一个服务,在这个服务中我应该检查我的主应用程序是处于活动状态还是在后台。有什么方法可以做到这一点吗?

4

3 回答 3

2

您可以扩展 Application 类并存储应用程序的当前状态。您需要从每个 Activity 的 onPause() 和 onResume() 方法中更新它。

public class MyApplication extends Application {

    public static boolean isAppVisible() {
      return visible;
   }  

    public static void inForeground() {
      visible = true;
    }

    public static void inBackground() {
      visible = false;
    }

    private static boolean visible;
}

在 AndroidManifest.xml 中注册您的应用程序类:

<application
    android:name="your.app.package.MyApplication"
    android:icon="@drawable/icon"
    android:label="@string/app_name" >

将 onPause 和 onResume 添加到项目中的每个 Activity(如果您愿意,可以为您的 Activity 创建一个公共超类,但如果您的 Activity 已经从 MapActivity/ListActivity 等扩展,您仍然需要手动编写以下内容) :

@Override
protected void onResume() {
    super.onResume();
    MyApplication.inBackground();
}

@Override
protected void onPause() {
    super.onPause();
    MyApplication.inForeground();
}
于 2013-04-15T09:44:10.193 回答
0
Context ctx = context.getApplicationContext();

ActivityManager am = (ActivityManager) context
        .getSystemService(ACTIVITY_SERVICE);

// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

PackageManager pm = this.getPackageManager();
boolean flag = false;
try {
    /**
     * take fore ground activity name
     */
    ComponentName componentInfo = taskInfo.get(0).topActivity;
    if (printLog) {
        Log.d("Tag", "CURRENT Activity ::"
                + taskInfo.get(0).topActivity.getClassName());
        Log.d("Tag", "Number Of Activities : "
                + taskInfo.get(0).numRunning);
        Log.d("Tag",
                "Componenet Info : " + componentInfo.getPackageName());
        Log.d("Tag",
                "Componenet Info : " + componentInfo.getClassName());
    }
    /**
     * All activities name of a package to compare with fore ground
     * activity. if match found, no notification displayed.
     */
    PackageInfo info = pm.getPackageInfo(
            "com.package_name",
            PackageManager.GET_ACTIVITIES);
    ActivityInfo[] list = info.activities;

    for (int i = 0; i < list.length; i++) {
        Log.d("Tag","Activity : "+list[i].name);

        if (list[i].name.equals(componentInfo.getClassName())) {
            flag = true;
        }
    }

    if(flag)
    {
        //activity is running
    }
} catch (NameNotFoundException e) {
    e.printStackTrace();
}

<uses-permission android:name="android.permission.GET_TASKS" />在清单中获得许可。

于 2013-04-15T09:44:56.327 回答
0

考虑使用 onPause() 和 onResume() 实现一个应用程序来跟踪应用程序是前进还是后退。
看看这个解决方案
希望能帮助到你。

于 2013-04-15T09:45:21.633 回答