5

Possible Duplicate:
How to detect when an Android app goes to the background and come back to the foreground

An Android app can have lots of actvities. I don't want to know when any old activity goes into the background, I want to know when any activity in the application goes into the background, and when any activity in the app comes into the foreground.

Do I have to handle onpause/onresume for each activity? Is there any easier way to do this?

Community
  • 1
  • 1
Mr. Awesome
  • 575
  • 1
  • 6
  • 19

3 Answers3

6

onPause() and onResume() are the methods to override. Check the activity lifecycle

Mohamed_AbdAllah
  • 5,311
  • 3
  • 28
  • 47
  • If I have 13 activites , i dont want to handle onPause and onResume for each one..is there an application wide equivalent? – Mr. Awesome Jan 24 '12 at 11:55
  • 1
    You could create a BaseActivity and derive all your activities from that one. This way you have to implement your handling only once. Nevertheless you might not be able to use this the approach, if you are using different subclasses of Activity. – henrik Jan 24 '12 at 12:08
  • Ok, I guess Chris Conway answer below (same as what henrik says) is your best bet – Mohamed_AbdAllah Jan 24 '12 at 12:24
  • I guess I'll have to brutally slog through each activity and override onpause and onresume. Thanks for the help gentlemen. – Mr. Awesome Jan 24 '12 at 12:27
  • Why, did you try the answer of Chris, you create a master activity (master onPause & onResume) for all activities and derive each activity from the master activity. – Mohamed_AbdAllah Jan 24 '12 at 12:29
1

If you're not experienced with lifecycles on Android it's worth going through the Notepad tutorials. Exercise 3 in particular goes into detail about activity lifecycle

1

Solve your problem with inheritance. To avoid overriding the lifecycle methods of all your activities, override it only in your parent.

public class ParentActivity extends Activity{
    public void onPause(){
      super.onPause();
      // do something
    }

    public void onResume(){
      super.onPause();
      // do something
    }  
}


public class ChildActivity extends ParentActivity{

   // onResume and onPause will be called automatically

}

Hope that helps!

Chris
  • 4,403
  • 4
  • 42
  • 54