I want to start a service when the users open my application, some of my activities need to bind the service, and when the users close my application, I stop the service.
The question is where can I stop the service. I want my service work when my app is open.
I start the service in Application.onCreate()
method, and I found there is no onDestroy()
method in Application
.
And I tried stop it in the launcher activity onDestroy
, but I don't think this is a good way because the system will recovery launcher activity when low memory.
What if you started and stopped your service based on running activities count? Here's an example.
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks {
private int startedActivitiesCount = 0;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
private void onAppStart() {
// Start service
}
private void onAppQuit() {
// Stop service
}
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
startedActivitiesCount++;
if (startedActivitiesCount == 1) {
onAppStart();
}
}
@Override
public void onActivityDestroyed(Activity activity) {
startedActivitiesCount--;
if (startedActivitiesCount == 0) {
onAppQuit();
}
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
}