1

I have a question in android. If my activity class interact with external library. This library which I'm working on it has to do some processes when the application go into background or when it returns to foreground.

Is there any way to know when the application enters the background.

NOTE: I don't want to do anything in the activity. I don't want to send callback to the library when onPause is invoked.

Thanks

Developer
  • 1,803
  • 2
  • 15
  • 26

4 Answers4

3

If I understood your problem, you could use Application.registerActivityLifecycleCallbacks and implement your own Application.ActivityLifecycleCallbacks.

Something like:

class myActivityLifecycleHandler implements ActivityLifecycleCallbacks{
  // Methods implementation here 
}

yourActivity.getApplication().registerActivityLifecycleCallbacks(new myActivityLifecycleHandler())
The Good Giant
  • 1,740
  • 2
  • 19
  • 35
  • 1
    Thanks alot, but this is for api 14 and higher I'm working in lower versions :) – Developer Apr 02 '13 at 17:20
  • 1
    I have the same problem and I honestly think that this is the only solution that does not involve writing code in the onStart(), onStop, etc.. A solution could be doing something as shown here (in the non-accepted answers): http://stackoverflow.com/questions/3183932/androidhow-to-check-if-application-is-running-in-background ..but I think it's feasible only if you don't have to continuosly check – The Good Giant Apr 03 '13 at 07:19
  • Thanks but unfortunately, in this case I have to check continuously.. because I want to do some events once the activity sent to background :) – Developer Apr 03 '13 at 08:27
0

You may write in some file when application coming to background.

Then your library may time for time checks this file.

QArea
  • 4,955
  • 1
  • 12
  • 22
0

Application.registerActivityLifecycleCallbacks is indeed the correct api that you want to use. Unfortunately it is indeed API14+, so you have the following option:

use this library to implement the activitylifecycle callback. You will have to extend your activities in the application you are working on, but something must be done to then no matter what as you need less than API14 support.

With this library implemented, you can create an int count in the callback. This count can be incremented and decremented every onStart() and onStop() callback for each activity. The count will go from 0 -> 1 on app open, and 1 -> 0 on app close/background. When these conditions are met you can do calls to your library.

Remember that when you background your app the OS can kill it off any time. If you have any amount of networking or anything long, start a service to handle it all as quickly as possible.

Glenn.nz
  • 2,261
  • 2
  • 17
  • 20
-1

override onPause method of activity, onPause is called when activity is going to backgroud

Saad Asad
  • 2,528
  • 3
  • 20
  • 27