Using Application context everywhere?

后端 未结 9 900
难免孤独
难免孤独 2020-11-22 01:52

In an Android app, is there anything wrong with the following approach:

public class MyApp extends android.app.Application {

    private static MyApp instan         


        
9条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 01:55

    I'm using the same approach, I suggest to write the singleton a little better:

    public static MyApp getInstance() {
    
        if (instance == null) {
            synchronized (MyApp.class) {
                if (instance == null) {
                    instance = new MyApp ();
                }
            }
        }
    
        return instance;
    }
    

    but I'm not using everywhere, I use getContext() and getApplicationContext() where I can do it!

提交回复
热议问题