How to Stop a Service Running as Foreground

What is the proper way to stop a service running as foreground

  1. From your activity, call startService(intent) and pass it some data representing a key to stop the service.
  2. From your service, call stopForeground(true)
  3. and then stopSelf() right after it.

How to properly stop a foreground service?

if you want to stop your service when you are clearing your application from the recent task, you have to define an attribute stopWithTask for service in the manifest file like this as shown below

  <service
android:enabled="true"
android:name=".ExampleService"
android:exported="false"
android:stopWithTask="true" />

then you can override onTaskRemoved method in the service , this will be called when the application's task is cleared

@Override
public void onTaskRemoved(Intent rootIntent) {
System.out.println("onTaskRemoved called");
super.onTaskRemoved(rootIntent);
//do something you want
//stop service
this.stopSelf();
}

How to end a foreground service only when app has been closed

I've found a solution, that at least seems to work for my situation. It's also a simple fix. In the same class that I override OnStartCommand, I've also done an override of OnTaskRemoved which is fired when a task from the service has been removed by the user. So when a user swipes to close the app, OnTaskRemoved will be called, where you can handle closing the service.

public override void OnTaskRemoved(Intent rootIntent)
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
{
StopForeground(StopForegroundFlags.Remove);
}
else
{
StopForeground(true);
}

StopSelf();

base.OnDestroy();
System.Diagnostics.Process.GetCurrentProcess().Kill();
}

How to stop a foreground service from the notification in android?

You don't need to create BroadCast to stop Service. Try this

private static final String ACTION_STOP_LISTEN = "action_stop_listen";
Intent intent = new Intent(this, ClosingBackGroundService.class);
intent.setAction(ACTION_STOP_LISTEN);
PendingIntent actionIntent = PendingIntent.getService(this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
addAction(R.mipmap.ic_launcher,"Close Services",actionIntent)

In onStartCommand check your Intent action

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && ACTION_STOP_LISTEN.equals(intent.getAction())) {
stopForeground(true);
stopSelf();
return START_NOT_STICKY;
}
// your code
}


Related Topics



Leave a reply



Submit