Friday, August 7, 2015

Android A better way to get Application Context anywhere in the app

Context reference is much needed everywhere in the application. Without this, it is going to be tough to do much of the processing such as registering receivers, posting notification etc. We can set the context when Activity starts to some static location, but the problem is that when the OS restarts the app, the Application context will be lost, this will be causing NPEs. Below code will give better way to get the context.
   
    import android.app.Application;
    import android.content.Context;
    import android.util.Log;
    
    public class MyApplication extends Application {
        
        private static Application sApplication;
        
        private static final String LOG_TAG = "EOMeApp";
        public static Application getApplication() {
            return sApplication;
        }
        
        public static Context getContext() {
            return getApplication().getApplicationContext();
        }
        
        @Override
        public void onCreate() {
            super.onCreate();
            Log.v(LOG_TAG,"On create of application");
            sApplication = this;
        }

    }

In the manifest file, in the Application tag, define the below 


android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name=".MyApplication">

references:
http://stackoverflow.com/questions/2002288/static-way-to-get-context-on-android

No comments:

Post a Comment