简体   繁体   中英

Technique for get the ApplicationContext anywhere

Recently I discovered a snippet that use the following technique in order to access statically from anywhere to the application context. It looks cool but is really a nice option or is a bad tech for some reason?

public class MyApp extends Application {
    private static MyApp instance;

    public static MyApp getInstance() {
        return instance;
    }

    public static Context getContext(){
        return instance.getApplicationContext();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }
}

除非你只是公开一个公共方法,它将一个Context作为一个参数,在你的类中需要Context (并从你的Activity传递它等),这就是这样做的方法。

This will certainly work. Just be careful as with using any singleton that you don't abuse it. Read the answer to this question explaining why the ApplicationContext is rarely (though sometimes) the right Context to use.

Also, having the ApplicationContext available everywhere allows you to be more sloppy with how you organize your classes since you won't need to think about what functionality really needs the ApplicationContext and whether you should factor that out, etc. That's just a maybe depending on how disciplined you are.

I'm always pretty wary of singletons although other notable people disagree, but I think it's still fairly widely debated whether singletons are a pattern or anti-pattern. If you Google singleton and anti-pattern you'll find articles like this which make some fairly good points in my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM