Android: Make use of Android Application Class as Singleton Object


Extending Android Application class is helpful when you would like to store session data or application wise global data.
In any android application, there will be only one application object, so you should you it as Singleton

MyAppApplication.java #29:
I called a method onAppCreated() and its an abstract method, that’s why i had to make the whole MyAppApplication as an abstract class
Reason:
the onAppCreated is particularly helpful when you will use library projects
For example, you would like to create an app with two versions liteand pro
Obviously there will be a lot of common features and pro version will have some additional features
so you are planning to make a library project named: CoreProject in android and make two sub classes named: appLite and appPro
Now suppose, you would like to know in your appLite that library project CoreProject is created successfully and then call a method
you can then easily implement onAppCreated() method in subclass appLite

MyAppApplication.java #32:
in initializeInstance(), you can do your app’s version wise specialized task
or may be something that you need to be done before the creation of your first activity

I have created and called screenConfiguration() method, which is used for determining the size of ScreenWidth and ScreenHeight
and it also helpful if you like to know the device is a tab or phone

MyAppApplication.java #67:
You may need to know if the app runs for the first time. suppose, you get to show the user the EULA (End User License Agreement) page for the first time.
In this case you can save the value in preferences and when the app get started you can call isFirstRun() to know if it is first time,
after that call setRunned() method, which will set the value false

MyAppApplication.java #80:
in onTerminate() method do your application wise clean up task
suppose, on close application you need to clear the user session data

display.getSize() is added and
display.getWidth(); display.getHeight();
are deprecated on API version 13

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
prevents the compilation error where minSdkVersion < 13

Application Class example


package com.example;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Point;
import android.os.Build;
import android.view.Display;
import android.view.WindowManager;

public abstract class MyAppApplication extends Application {

    private static MyAppApplication sInstance;
	
	SharedPreferences mPref;

    public static MyAppApplication getInstance() {
        return sInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;

        sInstance.initializeInstance();

        onAppCreated();
    }

    private void initializeInstance() {

        // Do your application wise initialization task
        screenConfiguration();
		
		// set application wise preference
		mPref = this.getApplicationContext().getSharedPreferences("pref_key", MODE_PRIVATE);
    }

    // particularly applicable in library projects
    public abstract void onAppCreated();

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public void screenConfiguration() {
        Configuration config = getResources().getConfiguration();
        boolean isTab = (config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;


        Point size = new Point();
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();

        int deviceScreenWidth;
        int deviceScreenHeight;

        try {
            display.getSize(size);
            deviceScreenWidth = size.x;
            deviceScreenHeight = size.y;
        } catch (NoSuchMethodError e) {
            deviceScreenWidth = display.getWidth();
            deviceScreenHeight = display.getHeight();
        }
    }
	
	public boolean isFirstRun() {
		// return true if the app is running for the first time 
        return mPref.getBoolean("is_first_run", true);
    }

    public void setRunned() {
		// after a successful run, call this method to set first run false 
        SharedPreferences.Editor edit = mPref.edit();
        edit.putBoolean("is_first_run", false);
        edit.commit();
    }

    @Override
    public void onTerminate() {
        // Do your application wise Termination task
        super.onTerminate();
    }
}

Here is a sample application tag from AndroidManifest file

AndroidManifest.xml


<application
        android:name="com.example.MyAppApplication"
        android:allowBackup="true"
        android:icon="@drawable/apps_logo" <!-- application logo -->
        android:logo="@drawable/action_bar_logo" <!-- action bar home logo -->
        android:label="@string/app_name"
        android:theme="@style/Theme.app_theme">

        <!-- other manifest elements goes here... -->

</application>
Advertisements

4 thoughts on “Android: Make use of Android Application Class as Singleton Object

  1. Howdy! I know this is kinda off topic however , I’d
    figured I’d ask. Would you be interested in exchanging
    links or maybe guest authoring a blog article or vice-versa?
    My website discusses a lot of the same subjects as yours and I feel
    we could greatly benefit from each other. If you’re interested feel free to shoot me
    an e-mail. I look forward to hearing from you!
    Great blog by the way!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s