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
Try use in AndroidManifest.xml:
<service android:name=".YourService" android:enabled="true" android:exported="true" />
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.
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>
....