SoFunction
Updated on 2025-03-01

Detailed explanation of Android global acquisition of Context instance

Detailed explanation of Android global acquisition of Context instance

Context is required when the Toast pops up, starts the activity, sends broadcasts, operates database, uses notifications, etc.

It is very simple if the operation is carried out in an activity, because the activity itself is a Context object

However, when the logical code is separated from the Activity class, using Context requires some skills:

We can customize our own Application class to manage some global status information in the program, such as global Context

The code is as follows:

public class MyApplication extends Application{
  
  private static Context context;

  @Override
  public void onCreate() {
    context = getApplicationContext();
  }
  public static Context getContext(){
    return context;
  }
}

Rewrite the parent class onCreate() method and get the application-level Context by calling the getApplicationContext() method.

Then provide a static getContext() method and return the retrieved Context

Note: Remember to initialize the MyApplication class under the <application> tag of the file

&lt;application
...
  android:name="com. ... .MyApplication"  &lt;——It is best to fill in the complete package name here
...
&lt;/application&gt;

This implements the mechanism of global acquisition of Context. You can use Context anywhere in the application just call ()

like:

((),"Global Context",Toast.LENGTH_SHORT).show();

If other Applications are used, you can call the initialization method of other Applications in the OnCreate() method in MyApplication

Thank you for reading, I hope it can help you. Thank you for your support for this site!