You should unbind service in B onStop(), then you can call stopService in A.
How to stop Service from another activity in Android?
-
03-06-2022 - |
質問
I have 2 activities, A & B. The Service starts in B with such code:
startService(new Intent(this, PlayerService.class));
Intent connectionIntent = new Intent(this, PlayerService.class);
bindService(connectionIntent, mp3PlayerServiceConnection, Context.BIND_AUTO_CREATE);
private ServiceConnection mp3PlayerServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
mp3Service = ((LocalBinder) binder).getService();
Thread t = new Thread() {
public void run() {
mp3Service.playSong(getApplicationContext(),url);
}
};
t.start();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
I need to have a possibility to close the service when I'm on activity A (B is closed, but music plays). How to call StopService from A onDestroy()? Need I to unbind it, if yes, how and where?
Simply putting stopService(new Intent(this,PlayerService.class));
leads to an error: Activity B has leaked Service connection ... that was originally bound here. (But B is already closed)
解決
他のヒント
So to clear some things up. Services can be of two types, not necessarily mutually exclusives.
These two types are started and bounded.
A STARTED service is one started with startService()
and is usually used to accomplish background operations that are somewhat independent from the flow of the activity. For ex,ample a service to download remote data may run independently from the activity that created it and then simply return the result when ready.
A started service keeps running until it stops itself.
A BOUNDED service is more like a client-server IPC pattern. For example an audio media player should be a bound service in order for the activity to be able to query the service about the state of the media player, e.g. track name, lenght...
A Bound Service lives as long as there is a component bound to it.
So, if your service is started, you should stop it from inside your service implementation with stopSelf()
or stopService()
. If it is bound, it stops himself when there is no more components bound to it. You unbind a service with unbindService()
. Note that a service can be both a started and a bound service!
For more information, refer to this:
http://developer.android.com/guide/components/services.html
Consider also using an IntentService
instead of a Service
in your application, since it seems that you don't need your service to be multithread.
you need to Unbind
the service
before destroying your Activity
. unbindService(myConnection);
Try unbindService()
in your onStop()