Android static Application.getInstance()

前端 未结 3 786
囚心锁ツ
囚心锁ツ 2021-01-04 17:56

Could you help me with this situation. We are using a static instance of a class that extends Application in android.

public class MyClass extends Applicatio         


        
3条回答
  •  情话喂你
    2021-01-04 18:48

    You should instantiate the singleton class with an other way (and not simply create a new object), in OnCreate method which is called when application starts:

    public class MyClass extends Application {
    
        // Singleton instance
        private static MyClass sInstance = null;
    
        @Override
        public void onCreate() {
            super.onCreate();
            // Setup singleton instance
            sInstance = this;
        }
    
        // Getter to access Singleton instance
        public static MyClass getInstance() {
            return sInstance ; 
        }
    }
    

    And be sure to link this class to application tag in Manifest.xml

    ...
    
    ...
    
    ....
    

提交回复
热议问题