How to call stopservice() method of Service class from the calling activity class
Solution 1:
In fact to stopping the service we must use the method stopService()
and you are doing in right way:
Start service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(myService);
Stop service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
stopService(myService);
if you call stopService()
, then the method onDestroy()
in the service is called (NOT the stopService()
method):
@Override
public void onDestroy() {
timer.cancel();
task.cancel();
Log.i(TAG, "onCreate() , service stopped...");
}
you must implement the onDestroy()
method!.
Here is a complete example including how to start/stop the service.
Solution 2:
I actually used pretty much the same code as you above. My service registration in the manifest is the following
<service android:name=".service.MyService" android:enabled="true">
<intent-filter android:label="@string/menuItemStartService" >
<action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
</intent-filter>
</service>
In the service class I created an according constant string identifying the service name like:
public class MyService extends ForeGroundService {
public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
...
}
and from the according Activity I call it with
startService(new Intent(MyService.MY_SERVICE));
and stop it with
stopService(new Intent(MyService.MY_SERVICE));
It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.
Solution 3:
@Juri
If you add IntentFilters for your service, you are saying you want to expose your service to other applications, then it may be stopped unexpectedly by other applications.