Sunday, April 22, 2012

How to maintain global application state

 

     In Android application, it’s sometimes important to keep a global application state. by global application state I mean to be able to have an entry point to the application which gives us a starter place to do stuff before the application starts. this is important in many aspects, for example, the application can start from different entry points, such as the launcher, a notification, or a service, or even by responding to a certain broadcast.

    There are many approaches to achieve this goal, one of them which a prefer is the Application Class, once extending the application class, we are able to load resources, setting different contexts , or even starting a certain service before the first activity starts, this is done simply by overriding the onCreate() method.

Example:

public class MyApplication extends Application {
boolean hasAgreed;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();

// get data from a db (you'll probably want to keep it in a static class
MyDatabase db = new MyDatabase();
ArrayList<MyObject> objects = (ArrayList<MyObject>) db.getMyObjects();


// start listening to location changes
LocationManager manager = (LocationManager) getSystemService(this.LOCATION_SERVICE);

// loading sharedpreferences and acting accordingly
SharedPreferences prefs = this.getSharedPreferences("my_shared_prefs", MODE_PRIVATE);

if (prefs.getBooelan("approved_agreement", false))
{
dosomething();
}
}
private void dosomething() {
// TODO Auto-generated method stub

}

}

So in the first part we are getting some data from our database to be able to store it in some static class for further use or processing.

In the second part we are staring to listen to location changes by getting a handle to the LocationManager

In the third part we are checking to see if the user has agreed to some agreement, this data is stored in the sharedPreferences, according to this value we can decide which Activity to fire or to do some other logic.

In addition, the Application class has ErrorListeners which can catch different errors from the context of the application and handle them form a single context.

In conclusion, the usage in the Application class is highly recommended and can make the development of android application to the next level.