Error
  • Copy failed
29January

Check Android Application resumed/paused

Check Android Application resumed/paused

Time goes by so fast, I was a little bit surprised to see that my last post was one month ago. So let's go..

Sometimes it is neccessary to get notfied if the application is sent to the background or recoveres back to foreground. As I started developing apps on iOS I was used that there is a central mechanism to check wheter the app is created, destroyed, started, stop etc. However in Android this central functionality is missing. So we need to implement a little workaround by implementing a base class every Activity inherits from.

For those who already use API level 14 or higher, the approach proposed by mjbshaw should be prefered unless follow the example shown in the implementation part below.

Implementation

public abstract class BaseActivity extends Activity 
{
	private static int mActiveActivityCounter = 0;
	
	private void startStuff()
	{
             //start stuff here
	}

    private void stopStuff()
	{
             //stop stuff here
	}
		
	@Override
	protected void onStart() 
    {
		super.onStart();
		if ( activeActivityCount() == 0 )
			startStuffStuff();

		++mActiveActivityCounter;
	}
	
	@Override
	protected void onStop()
	{
		super.onStop();
		--mActiveActivityCounter;
		
		if ( activeActivityCount() == 0 )
			stopStuff();
	}
		
	protected static int activeActivityCount()
	{
		return mActiveActivityCounter;
	}
	
	@Override
	protected void onResume() 
    {
		super.onResume();
		++mActiveActivityCounter;
	}

	@Override
	protected void onPause() 
    {
		super.onPause();
		--mActiveActivityCounter;
		
		if ( activeActivityCount() == 0 )
			stopStuff();
	}
}

 

If you have any notes, so feel free and leave me a comment ;)

 

cheers,
Chris

Posted in Blog, Android

Comments (0)

Leave a comment

You are commenting as guest. Optional login below.