I am trying to stop a service which is running as foreground service.
The current issue is that when I call stopService()
the notification still stays.
So in my solution I have added a receiver which I am registering to inside the onCreate()
Inside the onReceive()
method I call stopforeground(true)
and it hides the notification. And then stopself()
to stop the service.
Inside the onDestroy()
I unregistered the receiver.
Is there a more proper way to handle this? because stopService() simply doesn't work.
@Override public void onDestroy(){ unregisterReceiver(receiver); super.onDestroy(); }
To remove the service from the foreground, call stopForeground() . This method takes a boolean, which indicates whether to remove the status bar notification as well. Note that the service continues to run. If you stop the service while it's running in the foreground, its notification is removed.
You should put some flag inside your loop/computation method and call " return; " , and than You may stop service by stopself() or just wait untill it finish itself.
A started service must manage its own lifecycle. That is, the system doesn't stop or destroy the service unless it must recover system memory and the service continues to run after onStartCommand() returns. The service must stop itself by calling stopSelf() , or another component can stop it by calling stopService() .
Foreground services are an advanced Android concept which allows you to display notifications to your users when running long lived background tasks. The notification acts like any other notification, however it cannot be removed by the user and lives for the duration of the service.
From your activity call startService(intent)
and pass it some data that will represent a key to stop the service.
From your service call stopForeground(true)
and then stopSelf()
right after it.
to start and stop a foreground service from an activity use :
//start Intent startIntent = new Intent(MainActivity.this, ForegroundService.class); startIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION); startService(startIntent); //stop Intent stopIntent = new Intent(MainActivity.this, ForegroundService.class); stopIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION); startService(stopIntent);
in your foreground service - use (at least) this code:
@Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) { Log.i(LOG_TAG, "Received Start Foreground Intent "); // your start service code } else if (intent.getAction().equals( Constants.ACTION.STOPFOREGROUND_ACTION)) { Log.i(LOG_TAG, "Received Stop Foreground Intent"); //your end servce code stopForeground(true); stopSelfResult(startId); } return START_STICKY; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With