Static way to get 'Context' in Android?

前端 未结 19 2689
猫巷女王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:17

    According to this source you can obtain your own Context by extending ContextWrapper

    public class SomeClass extends ContextWrapper {
    
        public SomeClass(Context base) {
          super(base);
        }
    
        public void someMethod() {
            // notice how I can use "this" for Context
            // this works because this class has it's own Context just like an Activity or Service
            startActivity(this, SomeRealActivity.class);
    
            //would require context too
            File cacheDir = getCacheDir();
        }
    }
    

    JavaDoc for ContextWrapper

    Proxying implementation of Context that simply delegates all of its calls to another Context. Can be subclassed to modify behavior without changing the original Context.

提交回复
热议问题