Usage of Application class in android


Android applications can extend android.app.Application to have a application wide accessible class.

This class can be used as Controller. It can keep track of application state, global variables, etc.

First you’ll need to modify AndroidManifest.xml to register your application implementation.

<application android:icon="@drawable/launchericon"
        android:name="com.techjini.sample.android.SampleApplication"
        android:label="@string/app_name">
        <activity android:name="com.techjini.sample.android.activity.SplashActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

Now you can extend android.app.Application class and put some of your own methods to it.

/**
 *
 */
package com.techjini.sample.android;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.Log;

/**
 * @author anshu
 *
 */
public class SampleApplication extends Application {

    public static final boolean DEV_MODE = true;
    public static final int LOG_LEVEL = DEV_MODE ? Log.VERBOSE : Log.ERROR;

    /**
     * key to hold boolean whether application is registered.
     */
    private static final String UUID = "UUID";

    private ConnectivityManager connectivityManager;
    private SharedPreferences sharedPreferences;

    @Override
    public void onCreate() {
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        sharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE);
        super.onCreate();
    }

    public NetworkInfo getNetworkInfo() {
        return connectivityManager.getActiveNetworkInfo();
    }

    public NetworkInfo[] getAllNetworkInfo() {
        return connectivityManager.getAllNetworkInfo();
    }

    public boolean isRegistered() {
        return !sharedPreferences.getString(UUID, "0").equalsIgnoreCase("0");
    }

    public void setRegistered(String uuid) {
        Editor editor = sharedPreferences.edit();
        editor.putString(UUID, uuid);
    }

}

Here is the sample of how to use this application class from activity.

package com.techjini.sample.android.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.net.NetworkInfo;
import android.os.Bundle;

import com.techjini.sample.android.SampleApplication;

public class SplashActivity extends Activity implements Runnable {

    private static final int REGISTER_DIALOG = 0x0100;
    private static final int REGISTER_FAIL_DIALOG = 0x0101;

    private SampleApplication application;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        application = (SampleApplication) getApplication();
    }

    @Override
    protected void onResume() {
        TGLogger.d(this, "onResume");
        super.onResume();
        if (!application.isRegistered()) {
            NetworkInfo networkInfo = application.getNetworkInfo();
            if (networkInfo == null || !networkInfo.isAvailable()) {
                showDialog(REGISTER_FAIL_DIALOG);
                return;
            }
            showDialog(REGISTER_DIALOG);
            new Thread(this).run();
        }
    }

    @Override
    protected void onStop() {
        removeDialog(REGISTER_DIALOG);
        removeDialog(REGISTER_FAIL_DIALOG);
        super.onStop();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case REGISTER_DIALOG:
            return registerDialog();
        case REGISTER_FAIL_DIALOG:
            return registerFailDialog();
        }
        return super.onCreateDialog(id);
    }

    private Dialog registerFailDialog() {
        AlertDialog errorAlert;
        AlertDialog.Builder errorBuilder = new AlertDialog.Builder(this);
        errorBuilder.setMessage(getString(R.string.no_network_to_register));
        errorBuilder.setCancelable(false);
        errorBuilder.setPositiveButton(getString(R.string.okToUpdate),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();
                    }
                });
        errorAlert = errorBuilder.create();
        return errorAlert;
    }

    private Dialog registerDialog() {
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(getString(R.string.registering_user));
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(false);
        return progressDialog;
    }

    public void run() {

    }
}

You can see how Application instance is taken by getApplication() and simply type casted to our own Implementation.

Next question is how to get application instance in non UI classes(for example in database implementation).

You’ll need an instance of Context to get the instance of Application. If you have Context you can simply call context.getApplicationContext() and then typecast to your own implementation.

Advertisements

One comment

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