3

I'd like to detect when my application becomes paused (For example when the user press the home button or starts another application).

Some applications detect that situation and show a notification like: "The application .... is running in background". I need to do the same but for saving some objects in the database.

Thanks in advance

Caroline
  • 3,763
  • 5
  • 19
  • 25

4 Answers4

1

OnPause in the activity lifecycle is your answer. When your application is paused so is your activity.

Be careful not to do anything that will take a long amount of time. The OnPause method must complete before the next activity can start or resume. So if the user presses the home button, your OnPause has to complete before the user can see the launcher.

Phobos
  • 9,447
  • 3
  • 25
  • 30
0

Late on party...

You can implement the Application.ActivityLifecycleCallbacks interface and store which activities are being paused and resumed. New activities are resumed before old ones are paused, so basically, if the activity you get on onPaused is the same activity last recorded on onResume your app is going to the background. If onPause receives a different activity from the last one you recorded on onResume it means the user is navigating to another activity within your app.

0

You should deal with it in activity level. Please read following, especially comments in the first answer: Android: How to handle that the application is minimized by HOME button

Community
  • 1
  • 1
Tae-Sung Shin
  • 20,215
  • 33
  • 138
  • 240
-2

Just override following method in all the activity of your application.

protected void onPause() {     
  //do your work
  super.onPause();          
}
jainal
  • 2,973
  • 2
  • 20
  • 18