How do I check if I am pausing or exiting the appl

2019-08-08 02:29发布

问题:

I am currently writing an app for android that i need to start the service when I exit or pause the application. What should i do? In my application, every time when I click a thing, it will go to another activity, so i cannot put the startservice to the onpause inside those activity. What should I do?

回答1:

Have a look at the Activity life cycle here: http://developer.android.com/reference/android/app/Activity.html

Android doesn't exit the activity when you start a new one, it just pauses it. So starting the service inside onPause() should be fine.



回答2:

According to android life cycle, onPause() method will call as a first indication that user is leaving your activity. It may leave or not. So as per your requirement you can startService. But make sure don't put heavy code inside as it may effect user experience.



回答3:

By overriding this methods you can check if your app is onPause or onDestroy

protected void onPause() {
    Log.i("Status", "onPause");
    super.onPause();
}

protected void onDestroy() {
            Log.i("Status", "onDestroy");
    super.onDestroy();
}


回答4:

When Activity is no longer visible, it calls onStop(). But still we can not be sure if app is destroyed as Android OS internally handles it. So try following steps to find if you app is in background:

  1. Get the running task info using

    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    
  2. If tasks list is not empty, check if running taks belongs to your app. If it belongs, then return true to the calling function, where you can start your service ; else return false

     if (!tasks.isEmpty()) {
       ComponentName topActivity = tasks.get(0).topActivity;
      if (!topActivity.getPackageName().equals(context.getPackageName()))
      {
         return true;
      }
    

Edit : This may be helpful : http://developer.android.com/reference/android/app/ActivityManager.html#getRunningAppProcesses