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

AndroidForeground Service

Android Problem Overview


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();
}

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

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;
}

Solution 3 - Android

As stated here: https://developer.android.com/guide/components/services#Stopping

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().

Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.

So you can call stopService() from the activity that you used to call startService(). I have done that right here:

start_button.setOnClickListener {
            applicationContext.startForegroundService(Intent(this, ServiceTest::class.java))
        }
stop_button.setOnClickListener {
            applicationContext.stopService(Intent(this, ServiceTest::class.java))
        }

I created two buttons to start and stop the service and it works.

Solution 4 - Android

From Activity

 stopService(new Intent(this, ForegroundService.class));

From Service itself

  stopForeground(true);
  stopSelf()

Solution 5 - Android

In addition to other answers i ended with this snippet using android oreo and laters to stop job services.

Intent intent = new Intent(getApplicationContext(), LocationService.class);
intent.setAction(status);
ContextCompat.startForegroundService(getApplicationContext(), intent);

And in service

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
  startForeground(121, notification);
  if (intent.getAction().equals("StopService")) {
    stopForeground(true);
    stopSelf();
  }

startForeground() is mandatory unless app will crash without calling it

> The new Context.startForegroundService() method starts a foreground > service. The system allows apps to call > Context.startForegroundService() even while the app is in the > background. However, the app must call that service's > startForeground() method within five seconds after the service is > created.

https://developer.android.com/about/versions/oreo/android-8.0-changes.html

Solution 6 - Android

If you want to stop service and then update notification, you can first call stopSelf() and then notify(). stopForeground(false) makes the notification cancelable.

 private final BroadcastReceiver myBgWorkCompleteReceiver= new BroadcastReceiver() {
        @Override
  public void onReceive(Context context, Intent intent) {
            stopSelf();
            notificationLayoutExpanded.setTextViewText(R.id.file_download_notify_download_percentage, "Background work completed");
            manager.notify(mNotificationId, notification);
            stopForeground(false);
        }
};


 public void onDestroy() {
        super.onDestroy();
        // cancel any running threads here
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myBgWorkCompleteReceiver);
    }

Solution 7 - Android

I have found the best way to stop a service is to make stop itself. This way you are sure it actually will stop and preserve data integrity. If you want to do it from outside (activity) I usually use a global static attribute.

Check my answer here : https://stackoverflow.com/a/57833370/7795547

Solution 8 - Android

  • You can stop service from service or activity

From service:

 stopForeground(true);
 stopSelf();

From activity:

stopService(new Intent(this, MyService.class));
//MyService is your service

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1940676View Question on Stackoverflow
Solution 1 - AndroidIlya GazmanView Answer on Stackoverflow
Solution 2 - AndroidEladView Answer on Stackoverflow
Solution 3 - AndroidAhmed ShahidView Answer on Stackoverflow
Solution 4 - AndroidbeginnerView Answer on Stackoverflow
Solution 5 - AndroidNerius JokView Answer on Stackoverflow
Solution 6 - AndroidLincyTonitaView Answer on Stackoverflow
Solution 7 - AndroidD DimitrovView Answer on Stackoverflow
Solution 8 - AndroidSupremeApp Inc.View Answer on Stackoverflow