Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Service stops when Activity is closed

If I understand it correctly, bindService() with BIND_AUTO_CREATE will start a service and will not die until all bindings are all unbinded.

But if I bindService(BIND_AUTO_CREATE) at onCreate() and hit back button to close the activity, the service calls onDestroy() and dies also.

I don't call unbind() at anytime. So is that mean when the Activity got destroyed, the binding got destroyed also and the service gets destroyed also?

What if I want the service to be always running, at the same time when the activity starts I want to bind it so that I can access the service?

If I call StartService() and then bindService() at onCreate(), it will restart the service at every launch of Activity. (Which I don't want).

So I could I start service once and then bind next time I launch the activity?

like image 499
jclova Avatar asked Nov 23 '10 00:11

jclova


2 Answers

You need to use startService so that the service is not stopped when the activity that binds to it is destroyed.

startService will make sure that the service is running even if your activity is destroyed (unless it is stopped because of memory constraints). When you call startService, the onStart method is called on the service. It doesn't restart (terminate and start again) the service. So it depends on how you implement the onStart method on the Service. The Service's onCreate, however, is only called once, so you may want to initialize things there.

like image 72
Randy Sugianto 'Yuku' Avatar answered Sep 21 '22 07:09

Randy Sugianto 'Yuku'


I found a solution!

The problem is when you close your activity and your service is not configured as a foreground service, android system will recognize it as unused and close it.

here's an example where I added a notification :

void setUpAsForeground(String text) {
    PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
            new Intent(getApplicationContext(), MainActivity.class),
            PendingIntent.FLAG_UPDATE_CURRENT);
    mNotification = new Notification();
    mNotification.tickerText = text;
    mNotification.icon = R.drawable.muplayer;
    mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
    mNotification.setLatestEventInfo(getApplicationContext(), "MusicPlayer",
            text, pi);
    startForeground(NOTIFICATION_ID, mNotification);

}

(A foreground service is a service that's doing something the user is actively aware of (such as playing music), and must appear to the user as a notification. That's why we create the notification here)

like image 38
Khalil Kitar Avatar answered Sep 22 '22 07:09

Khalil Kitar