应用程序进入后台时启动服务

时间:2015-03-18 08:56:59

标签: android android-service

我有一个应用程序包含一些活动,以及应该在整个应用程序进入后台时启动的服务。 现在我在主活动调用onStop方法时启动服务,但是当我开始我的应用程序的新活动时也会调用此方法(在这种情况下,服务不应该启动)。 有一种方法可以检查我的应用程序(不是特定活动)何时进入后台,或者我需要检查每项活动?

2 个答案:

答案 0 :(得分:0)

private boolean isApplicationBroughtToBackground() {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }

    return false;
}

了解更多信息see this

答案 1 :(得分:0)

嘿,你必须为此创建一个应用程序级别的类,并为每个屏幕设置布尔值,我将向您展示如何在单个屏幕或活动中进行....

public class MyApplication extends Application {

private static boolean mainActivityVisible;

public static boolean isMainActivityVisible() {
    return mainActivityVisible;
}  

public static void mainActivityResumed() {
    mainActivityVisible = true;
}

public static void mainActivityPaused() {
    mainActivityVisible = false;
}

}

然后在MainActivity中

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    MyApplication.mainActivityPaused();
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    MyApplication.mainActivityResumed();
}

@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();
  if(isAppRunning(context))
    {
        if(MyApplication.isMainActivityVisible())
        {
           //Means activity not in background so dont start service or broadcasting
        }
        else
        {
          //Means activity is in background so start service here..
         } 
    }
    else
    {
       //Means app is not alive...so start also service here
    }
}

方法isAppRunning here

public static boolean isAppRunning(Context context) {
    // check with the first task(task in the foreground)
    // in the returned list of tasks
    ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> services = activityManager
.getRunningTasks(Integer.MAX_VALUE);
    if (services.get(0).topActivity.getPackageName().toString()
.equalsIgnoreCase(context.getPackageName().toString())) 
    {
        return true;
    }
    return false;
}