views:

127

answers:

5

How can I tell that my application has been put in the background (i.e. none of my app's activities are visible anymore)? I need to determine this so that I can release resources shared among several of my activities (graphics, sound clips and a socket connection).

I've thought about keeping a global counter that's incremented in the activities' onStart() method, and decremented in onStop(). If the counter reaches zero, then all activities have been stopped and my app is running in the background. However I'm not sure if this is going to be 100% reliable. Also, I can't help but think that there must be a better way of doing this.

A: 

You could use a global counter assuming it is kept in persistent storage. Always keep in mind the system is free to unload and reload activities from device RAM based on pressure from other apps so instance variables of activities are probably not a good choice to house that data.

I think the Android way of handling a scenario like yours would be to manage your connection state in a service and use persistent storage to monitor application state.

ktingle
Using a service for this seems a bit heavyweight. Also, it's not just a connection that needs to be released, there's also other resources shared among my activities such as graphics and sound clips that I'd like to release when my app goes in the background (I'll edit this in to my question).Of course the counter wouldn't be kept in an Activity instance variable. It would probably live in the custom Application class I have in my app, which of course will persist for the entire lifetime of my app.
Haakon
A: 

If you need this functionality maybe your architecture is not well designed. Each activity must be in some way "standalone" so when it's stopped release any data associate with it. If you need to store some persistant data between activities use sql or some other data storage and if you need some shared resources between activities put them in service. Try to isolate any coupling between activities.

Mojo Risin
+1  A: 

You shouldn't need to know this, but to answer you:

in your main activity:

public boolean inBackground;

@Override
public void onPause()
{
     inBackground=true;
     super.onPause();
}

@Override
public void onResume()
{
     inBackground=false;
     super.onResume();
}
raybritton
A: 

Get the running tasks from activity manager and get their package names to see if it matches the package names of your application.