Static way to get 'Context' in Android?

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

    If you don't want to modify the manifest file, you can manually store the context in a static variable in your initial activity:

    public class App {
        private static Context context;
    
        public static void setContext(Context cntxt) {
            context = cntxt;
        }
    
        public static Context getContext() {
            return context;
        }
    }
    

    And just set the context when your activity (or activities) start:

    // MainActivity
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // Set Context
        App.setContext(getApplicationContext());
    
        // Other stuff
    }
    

    Note: Like all other answers, this is a potential memory leak.

提交回复
热议问题