Using Application context everywhere?

后端 未结 9 888
难免孤独
难免孤独 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条回答
  •  既然无缘
    2020-11-22 02:13

    I like it, but I would suggest a singleton instead:

    package com.mobidrone;
    
    import android.app.Application;
    import android.content.Context;
    
    public class ApplicationContext extends Application
    {
        private static ApplicationContext instance = null;
    
        private ApplicationContext()
        {
            instance = this;
        }
    
        public static Context getInstance()
        {
            if (null == instance)
            {
                instance = new ApplicationContext();
            }
    
            return instance;
        }
    }
    

提交回复
热议问题