Android Get Application Context From Anywhere Example

When your android application grows, there are a lot of util classes. And sometime you need to use android application context in those classes to do something like create Toast message or create Snackbar popup. And if you pass the context object as input parameter to every util class, you will find that it is impossible and complex. This article will tell you how to retrieve android app context object in any util class when you need.

As you can see in AndroidManifest.xml file, each android app will declare a unique application xml element in it like below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dev2qa.example">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name">
        
        <activity....>
           ......
        </activity>
    </application>

</manifest>

So the best method to resolve this issue is to define a custom application object ( extends android.app.Application ) and use it in your AndroidManifest.xml file like below.

1. Create The Global Application Sub Class.

GlobalApplication.java

package com.dev2qa.example.application;

import android.app.Application;
import android.content.Context;

/**
 * Created by Jerry on 3/21/2018.
 */

public class GlobalApplication extends Application {

    private static Context appContext;

    @Override
    public void onCreate() {
        super.onCreate();
        appContext = getApplicationContext();

        /* If you has other classes that need context object to initialize when application is created,
         you can use the appContext here to process. */
    }

    public static Context getAppContext() {
        return appContext;
    }
}

2. Use Above Custom Application In Android Manifest Xml File.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.dev2qa.example"> 
      <application 
       android:name="com.dev2qa.example.application.GlobalApplication"
       android:allowBackup="true" 
       android:icon="@mipmap/ic_launcher" 
       android:label="@string/app_name"> 
         <activity....>
            ......
         </activity>
     </application> 
</manifest>

3. Retrieve Application Context Anywhere In Java Class.

Then you can use below code to get this android app context object anywhere in your java util class and use it when you need.

Context context = GlobalApplication.getAppContext();

Toast.make(context, "Hello global context. ", Toast.LENGTH_LONG).show();
(Visited 3,424 times, 26 visits today)
READ :   Android Contacts Fields, Data Table Columns And Data Mimetype Explain

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.