Android programming the method that gets the global Context

  • 2020-12-22 17:46:16
  • OfStack

This article gives an example of how Android programming gets the global Context. To share for your reference, the details are as follows:

Sometimes the Context object is needed when dealing with business logic, but in some cases it is not easy to obtain, so some clever tricks are needed to manage Context.

In Android, there is a class called Application that is automatically initialized when the application starts, so we can write our own Application class to manage some of the global state information.

Here, take getting the global Context as an example.

1. Write your own Application class


package com.example.testapplication;
import android.app.Application;
import android.content.Context;
/**
 *  Write your own Application , to manage global state information, for example Context
 * @author yy
 *
 */
public class MyApplication extends Application {
  private static Context context;
  @Override
  public void onCreate() {
    // To obtain Context
    context = getApplicationContext();
  }
  // return 
  public static Context getContextObject(){
    return context;
  }
}

Next, the system needs to be told that the MyApplication class should be initialized when the program starts, rather than the default Application class.

2. Modify the AndroidManifest.xml file

Modify the application attribute:


<application
  android:name="com.example.testapplication.MyApplication"
   ....
  >

This implements the mechanism for obtaining Context globally.

3, use,

Wherever used, you can get the Context object using the following:

MyApplication.getContextObject();

I hope this article has been helpful in Android programming.


Related articles: