I have the following code in each of the 5 activities of my app. I wanted to keep the service running that is bound to these five activities. It will play music in the background. However when the user navigates away from the any of these five activities the Service should be killed. Using the code below I am able to get it so that the music plays in the background when navigating between the activities. but the Service keeps running after leaving the application. What is the best way to solve this problem? How about some creative ideas.

I put this Toast message in the onDestroy method of the service so I can tell when the service is stopped.

 Toast.makeText(this, "My Service Destroyed", Toast.LENGTH_LONG).show();

I never see any Toast message pop up when I leave the application. The other toast messages do show to indicate that the service has started.

@Override
public void onPause() {
    super.onPause();
    unbindService(serviceConnection);
}

@Override
public void onResume() { 
    //After a pause OR at startup
    super.onResume();
    //add this to the onResume of the activity
    //  startService(new Intent(this, AudioService.class));
    bindService(new Intent(this, AudioService.class), 
                  serviceConnection, Context.BIND_AUTO_CREATE);

}
有帮助吗?

解决方案

According to the documentation here:

Multiple clients can bind to the service at once. When a client is done interacting with the service, it calls unbindService() to unbind. Once there are no clients bound to the service, the system destroys the service.

So maybe you're missing some unbind in one of your activities. You can check this by printing a log in the onBind and onUnbind methods of your service.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top