Can I use static method to get context on Android?

Asked 2 years ago, Updated 2 years ago, 133 views

I'd like to use a static method to get a context. How do I do it

android android-context

2022-09-21 18:47

1 Answers

First of all, the Android Manifest file is

<application android:name="com.xyz.MyApplication">

</application>

If it's like this

public class MyApplication extends Application {

    private static Context context;

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

    public static Context getAppContext() {
    return MyApplication.context;
    }
}

Do it like this. If you use MyApplication.getAppContext(), you can get it statically anywhere.


2022-09-21 18:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.