Android-Get Context globally

When we are using the database, using Toast, when launching activities, etc., we all need to Context.
Sometimes when the code becomes more complex, we will start to worry about getting the context.
Solution:
Create a MyApplication class to inherit the Applicationle class and
override the parent class. onCreate() method, and call getApplicationContext() method to obtain an application-level Context and assign it to the context we established

public class MyApplication extends Application {
    private static Context context;

    public static Context getContext() {
        return context;
    }

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

Then reference the get method where you need to use it

MyApplication.getContext()

You also need to configure a sentence for the application tag in the manifest file, the purpose is to initialize the MyApplication class when the program starts

 android:name="com.example.lambda.MyApplication"

Guess you like

Origin blog.csdn.net/News53231323/article/details/113808258