Android static Application.getInstance()

前端 未结 3 707
囚心锁ツ
囚心锁ツ 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:38

    Try use in AndroidManifest.xml:

    <service android:name=".YourService" android:enabled="true" android:exported="true" />
    
    0 讨论(0)
  • 2021-01-04 18:45

    You can't (or at least SHOULD NOT) create an instance of Application explicitly. Every 'app' has a single instance of Application which is created by the OS when you start the app. This happens whether you choose to extend Application or not (what do you think the Context returned by getApplicationContext() references?).

    If you want your Application to main a static object then it's as simple as this...

    public class MyClass extends Application {
    
        private MyObject mObject = null;
    
        public static MyObject getMyObject() {
            if (mObject == null)
                mObject = new MyObject;
            return mObject;
        }
    }
    

    From anywhere in your code you can then just use...

    MyClass.getMyObject();
    

    ...to get an instance of your object.

    0 讨论(0)
  • 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

    ...
    <application
        android:name="package.MyClass"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
    ...
    </application>
    ....
    
    0 讨论(0)
提交回复
热议问题