android如何检查我的应用程序是否仍在运行

时间:2015-09-15 12:31:27

标签: android

我想创建一个处理程序,或者想要检查应用程序是否仍在运行,例如

while(appIsRunning)
 {

 //do something

 }
do somthimg

2 个答案:

答案 0 :(得分:1)

使用“ActivityLifecycleCallbacks”并以这种方式使用它:

    public class MyApplication extends Application {

     @Override
     public void onCreate (){
     super.onCreate();
     registerActivityLifecycleCallbacks(new MyActivityLifecycleCallbacks());
     }

        @Override
        public void onTerminate (){
         super.onTerminate();
        }

        @Override
        public void onConfigurationChanged (Configuration newConfig){
         super.onConfigurationChanged(newConfig);
        }

        private static final class MyActivityLifecycleCallbacks implements ActivityLifecycleCallbacks {

      public void onActivityCreated(Activity activity, Bundle bundle) {
       Log.e("","onActivityCreated:" + activity.getLocalClassName());
      }

      public void onActivityDestroyed(Activity activity) {
       Log.e("","onActivityDestroyed:" + activity.getLocalClassName());
      }

      public void onActivityPaused(Activity activity) {
       Log.e("","onActivityPaused:" + activity.getLocalClassName());
      }

      public void onActivityResumed(Activity activity) {
       Log.e("","onActivityResumed:" + activity.getLocalClassName());
      }

      public void onActivitySaveInstanceState(Activity activity,
        Bundle outState) {
       Log.e("","onActivitySaveInstanceState:" + activity.getLocalClassName());
      }

      public void onActivityStarted(Activity activity) {
       Log.e("","onActivityStarted:" + activity.getLocalClassName());
      }

      public void onActivityStopped(Activity activity) {
       Log.e("","onActivityStopped:" + activity.getLocalClassName());
      }
        }
    }

通过这种方式,您可以检查每个州并做任何事情......

答案 1 :(得分:-1)

试试这个

public static boolean isAppRunning(Context context) 
    {
        ActivityManager activityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager
            .getRunningAppProcesses();
        for (RunningAppProcessInfo appProcess : appProcesses) 
         {
            if (appProcess.processName.equals(context.getPackageName())) 
            {
                if (appProcess.importance != RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE) 
                {
                    return true;
                } 
            }
        }
        return false;
    }