Static way to get 'Context' in Android?

前端 未结 19 3060
猫巷女王i
猫巷女王i 2020-11-21 06:36

Is there a way to get the current Context instance inside a static method?

I\'m looking for that way because I hate saving the \'Context\' instance eac

19条回答
  •  半阙折子戏
    2020-11-21 07:24

    You can use the following:

    MainActivity.this.getApplicationContext();
    

    MainActivity.java:

    ...
    public class MainActivity ... {
        static MainActivity ma;
    ...
        public void onCreate(Bundle b) {
             super...
             ma=this;
             ...
    

    Any other class:

    public ...
        public ANY_METHOD... {
             Context c = MainActivity.ma.getApplicationContext();
    

提交回复
热议问题