Android: The service stops when activity is closed.

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

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

I do not call unbind () at any time. So this means that when the action was destroyed, the binding was also destroyed and the service was also destroyed?

What if I want the service to always work, at the same time that the action starts. I want to link it in order to access the service?

If I call StartService () and then bindService () in onCreate (), it will restart the service every time the Activity starts. (Which I do not want).

So, could I start the service once and then bind the next time when I start the action?

+7
android service bind
source share
3 answers

You need to use startService so that the service does not stop when activities associated with it are destroyed.

startService will guarantee that the service will be started even if your activity is destroyed (if it is not stopped due to memory limitations). When you call startService , the onStart method is called in the service. It does not restart (terminates and does not start again) the service. Therefore, it depends on how you implement the onStart method on the Service. The onCreate service, however, is called only once, so you can initialize things there.

+9
source share

I have found a solution!

The problem is that when you close your activity and your service is not configured as a foreground service, the Android system recognizes it as unused and closes it.

here is 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 does something that the user is actively aware of (for example, plays music) and should appear to the user as a notification. That's why we create a notification here)

+4
source share

You can do this using BroadcastReceivers. You will find many on Google how to use them.

-5
source share

All Articles