How to stop a service from another activity in Android?

I have 2 actions, A and B. The service starts with B with this 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 be able to close the service when I am on activity A (B is closed, but the music is playing). How to call StopService from A onDestroy ()? Do I need to unlock it, if so, how and where?

Simple placement stopService(new Intent(this,PlayerService.class)); leads to an error: in action B, a service connection leaked ... which was originally connected here. (But B is already closed)

+6
source share
4 answers

You must disable the service in B onStop (), then you can call stopService in A.

+4
source

So, to clear some things. Services can be of two types, not necessarily mutually exclusive.

These two types are triggered and limited.

The STARTED service starts with startService() and is usually used to perform background operations, which are somewhat independent of the activity flow. For example, an extensive service for downloading remote data can be launched regardless of the activity it creates, and then simply return the result when ready.

The initial service continues to run until it stops.

The BOUNDED service is more like an IPC client-server pattern. For example, an audio player should be a related service so that activity can request a service about the state of a media player, for example. track name, length ...

A Bound Service works as long as there is a component associated with it.

So, if your service is running, you must stop it from your implementation using stopSelf() or stopService() . If it is connected, it stops when there are no components associated with it. You unbind the service using unbindService() . Please note that the service may be a running and related service!

For more information, see the following:

http://developer.android.com/guide/components/services.html

Consider also using IntentService instead of Service in your application, as it seems that you do not need your service for multithreading.

+3
source

You need Unbind service before destroying your Activity . unbindService(myConnection);

+1
source

Try unbindService() in onStop()

+1
source

Source: https://habr.com/ru/post/949593/


All Articles