Skip to content Skip to sidebar Skip to footer

How Do I Check If I Am Pausing Or Exiting The Application For Android

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 thin

Solution 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.

Solution 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.

Solution 3:

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

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

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

Solution 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

    ActivityManageram= (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()))
      {
         returntrue;
      }
    

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

Post a Comment for "How Do I Check If I Am Pausing Or Exiting The Application For Android"