How to properly stop a foreground service?












0















I use startForeground to make my service "persist" in background and not be killed by the OS.

I remove the service in the main activity onDestroy method by calling stopForeground and stopService.
The problem is, when I swipe my app off the recent apps to kill it, the debug session is still running, whereas in the "normal" functioning (without using startForeground), the debug session terminates correctly.

Using adb shell confirms that the app is still running.

startForeground somehow creates a "special" running thread that could not be stopped by simply stopping the foreground and the service.

Any ideas please ?










share|improve this question





























    0















    I use startForeground to make my service "persist" in background and not be killed by the OS.

    I remove the service in the main activity onDestroy method by calling stopForeground and stopService.
    The problem is, when I swipe my app off the recent apps to kill it, the debug session is still running, whereas in the "normal" functioning (without using startForeground), the debug session terminates correctly.

    Using adb shell confirms that the app is still running.

    startForeground somehow creates a "special" running thread that could not be stopped by simply stopping the foreground and the service.

    Any ideas please ?










    share|improve this question



























      0












      0








      0








      I use startForeground to make my service "persist" in background and not be killed by the OS.

      I remove the service in the main activity onDestroy method by calling stopForeground and stopService.
      The problem is, when I swipe my app off the recent apps to kill it, the debug session is still running, whereas in the "normal" functioning (without using startForeground), the debug session terminates correctly.

      Using adb shell confirms that the app is still running.

      startForeground somehow creates a "special" running thread that could not be stopped by simply stopping the foreground and the service.

      Any ideas please ?










      share|improve this question
















      I use startForeground to make my service "persist" in background and not be killed by the OS.

      I remove the service in the main activity onDestroy method by calling stopForeground and stopService.
      The problem is, when I swipe my app off the recent apps to kill it, the debug session is still running, whereas in the "normal" functioning (without using startForeground), the debug session terminates correctly.

      Using adb shell confirms that the app is still running.

      startForeground somehow creates a "special" running thread that could not be stopped by simply stopping the foreground and the service.

      Any ideas please ?







      android service foreground-service






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 12:30









      Fantômas

      32.8k156490




      32.8k156490










      asked Nov 16 '18 at 8:43









      Mahmoud MasmoudiMahmoud Masmoudi

      268




      268
























          2 Answers
          2






          active

          oldest

          votes


















          1














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





          share|improve this answer
























          • Thank you ! That's exactly what I wanted to do :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:25



















          0














          I don't know if it's correct but on my app i'm stopping the foreground service here and it works.Check the code



          private void stopForegroundService() {

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }


          UPDATE



          Call the stopservice from your main class somehow(not from onDestroy) like this:



              Intent intent = new Intent(this, MyForeGroundService.class);
          intent.setAction(MyForeGroundService.ACTION_STOP_FOREGROUND_SERVICE);
          startService(intent);


          MyForegroundService.java



           private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";

          public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";

          public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";

          @Override
          public int onStartCommand(Intent intent, int flags, int startId) {
          if (intent != null) {
          String action = intent.getAction();

          switch (action) {
          case ACTION_START_FOREGROUND_SERVICE:
          startForegroundService();
          break;
          case ACTION_STOP_FOREGROUND_SERVICE:

          stopForegroundService();
          break;
          }
          }
          return START_STICKY;
          }

          private void stopForegroundService() {
          Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }





          share|improve this answer


























          • I have just tried it and the output is the same. Did you try to kill your app by swiping it off the recent apps while debugging and while your service is running ? Just to see if the debug session is properly stopped

            – Mahmoud Masmoudi
            Nov 16 '18 at 8:57











          • @MahmoudMasmoudi You said you've implemented it in onDestroy()? try call this method from inside your service class.Check the updated answer.I hope it helps

            – Alex Kolydas
            Nov 16 '18 at 9:11













          • Thank you for your reply. This should work. However, it can not detect when the user has swiped off the app from "recent apps" (That's why I had to put this in the activity's onDestroy method)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:24











          • I'm sorry i don't know how to help you more :/ I hope you finally find your answer

            – Alex Kolydas
            Nov 16 '18 at 14:45











          • No worries. I appreciate your help :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 15:52












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334235%2fhow-to-properly-stop-a-foreground-service%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














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





          share|improve this answer
























          • Thank you ! That's exactly what I wanted to do :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:25
















          1














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





          share|improve this answer
























          • Thank you ! That's exactly what I wanted to do :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:25














          1












          1








          1







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





          share|improve this answer













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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 16 '18 at 9:19









          Hasif SeydHasif Seyd

          1,034817




          1,034817













          • Thank you ! That's exactly what I wanted to do :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:25



















          • Thank you ! That's exactly what I wanted to do :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:25

















          Thank you ! That's exactly what I wanted to do :)

          – Mahmoud Masmoudi
          Nov 16 '18 at 13:25





          Thank you ! That's exactly what I wanted to do :)

          – Mahmoud Masmoudi
          Nov 16 '18 at 13:25













          0














          I don't know if it's correct but on my app i'm stopping the foreground service here and it works.Check the code



          private void stopForegroundService() {

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }


          UPDATE



          Call the stopservice from your main class somehow(not from onDestroy) like this:



              Intent intent = new Intent(this, MyForeGroundService.class);
          intent.setAction(MyForeGroundService.ACTION_STOP_FOREGROUND_SERVICE);
          startService(intent);


          MyForegroundService.java



           private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";

          public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";

          public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";

          @Override
          public int onStartCommand(Intent intent, int flags, int startId) {
          if (intent != null) {
          String action = intent.getAction();

          switch (action) {
          case ACTION_START_FOREGROUND_SERVICE:
          startForegroundService();
          break;
          case ACTION_STOP_FOREGROUND_SERVICE:

          stopForegroundService();
          break;
          }
          }
          return START_STICKY;
          }

          private void stopForegroundService() {
          Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }





          share|improve this answer


























          • I have just tried it and the output is the same. Did you try to kill your app by swiping it off the recent apps while debugging and while your service is running ? Just to see if the debug session is properly stopped

            – Mahmoud Masmoudi
            Nov 16 '18 at 8:57











          • @MahmoudMasmoudi You said you've implemented it in onDestroy()? try call this method from inside your service class.Check the updated answer.I hope it helps

            – Alex Kolydas
            Nov 16 '18 at 9:11













          • Thank you for your reply. This should work. However, it can not detect when the user has swiped off the app from "recent apps" (That's why I had to put this in the activity's onDestroy method)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:24











          • I'm sorry i don't know how to help you more :/ I hope you finally find your answer

            – Alex Kolydas
            Nov 16 '18 at 14:45











          • No worries. I appreciate your help :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 15:52
















          0














          I don't know if it's correct but on my app i'm stopping the foreground service here and it works.Check the code



          private void stopForegroundService() {

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }


          UPDATE



          Call the stopservice from your main class somehow(not from onDestroy) like this:



              Intent intent = new Intent(this, MyForeGroundService.class);
          intent.setAction(MyForeGroundService.ACTION_STOP_FOREGROUND_SERVICE);
          startService(intent);


          MyForegroundService.java



           private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";

          public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";

          public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";

          @Override
          public int onStartCommand(Intent intent, int flags, int startId) {
          if (intent != null) {
          String action = intent.getAction();

          switch (action) {
          case ACTION_START_FOREGROUND_SERVICE:
          startForegroundService();
          break;
          case ACTION_STOP_FOREGROUND_SERVICE:

          stopForegroundService();
          break;
          }
          }
          return START_STICKY;
          }

          private void stopForegroundService() {
          Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }





          share|improve this answer


























          • I have just tried it and the output is the same. Did you try to kill your app by swiping it off the recent apps while debugging and while your service is running ? Just to see if the debug session is properly stopped

            – Mahmoud Masmoudi
            Nov 16 '18 at 8:57











          • @MahmoudMasmoudi You said you've implemented it in onDestroy()? try call this method from inside your service class.Check the updated answer.I hope it helps

            – Alex Kolydas
            Nov 16 '18 at 9:11













          • Thank you for your reply. This should work. However, it can not detect when the user has swiped off the app from "recent apps" (That's why I had to put this in the activity's onDestroy method)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:24











          • I'm sorry i don't know how to help you more :/ I hope you finally find your answer

            – Alex Kolydas
            Nov 16 '18 at 14:45











          • No worries. I appreciate your help :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 15:52














          0












          0








          0







          I don't know if it's correct but on my app i'm stopping the foreground service here and it works.Check the code



          private void stopForegroundService() {

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }


          UPDATE



          Call the stopservice from your main class somehow(not from onDestroy) like this:



              Intent intent = new Intent(this, MyForeGroundService.class);
          intent.setAction(MyForeGroundService.ACTION_STOP_FOREGROUND_SERVICE);
          startService(intent);


          MyForegroundService.java



           private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";

          public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";

          public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";

          @Override
          public int onStartCommand(Intent intent, int flags, int startId) {
          if (intent != null) {
          String action = intent.getAction();

          switch (action) {
          case ACTION_START_FOREGROUND_SERVICE:
          startForegroundService();
          break;
          case ACTION_STOP_FOREGROUND_SERVICE:

          stopForegroundService();
          break;
          }
          }
          return START_STICKY;
          }

          private void stopForegroundService() {
          Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }





          share|improve this answer















          I don't know if it's correct but on my app i'm stopping the foreground service here and it works.Check the code



          private void stopForegroundService() {

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }


          UPDATE



          Call the stopservice from your main class somehow(not from onDestroy) like this:



              Intent intent = new Intent(this, MyForeGroundService.class);
          intent.setAction(MyForeGroundService.ACTION_STOP_FOREGROUND_SERVICE);
          startService(intent);


          MyForegroundService.java



           private static final String TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE";

          public static final String ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE";

          public static final String ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE";

          @Override
          public int onStartCommand(Intent intent, int flags, int startId) {
          if (intent != null) {
          String action = intent.getAction();

          switch (action) {
          case ACTION_START_FOREGROUND_SERVICE:
          startForegroundService();
          break;
          case ACTION_STOP_FOREGROUND_SERVICE:

          stopForegroundService();
          break;
          }
          }
          return START_STICKY;
          }

          private void stopForegroundService() {
          Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");

          // Stop foreground service and remove the notification.
          stopForeground(true);

          // Stop the foreground service.
          stopSelf();
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 16 '18 at 9:10

























          answered Nov 16 '18 at 8:48









          Alex KolydasAlex Kolydas

          346317




          346317













          • I have just tried it and the output is the same. Did you try to kill your app by swiping it off the recent apps while debugging and while your service is running ? Just to see if the debug session is properly stopped

            – Mahmoud Masmoudi
            Nov 16 '18 at 8:57











          • @MahmoudMasmoudi You said you've implemented it in onDestroy()? try call this method from inside your service class.Check the updated answer.I hope it helps

            – Alex Kolydas
            Nov 16 '18 at 9:11













          • Thank you for your reply. This should work. However, it can not detect when the user has swiped off the app from "recent apps" (That's why I had to put this in the activity's onDestroy method)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:24











          • I'm sorry i don't know how to help you more :/ I hope you finally find your answer

            – Alex Kolydas
            Nov 16 '18 at 14:45











          • No worries. I appreciate your help :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 15:52



















          • I have just tried it and the output is the same. Did you try to kill your app by swiping it off the recent apps while debugging and while your service is running ? Just to see if the debug session is properly stopped

            – Mahmoud Masmoudi
            Nov 16 '18 at 8:57











          • @MahmoudMasmoudi You said you've implemented it in onDestroy()? try call this method from inside your service class.Check the updated answer.I hope it helps

            – Alex Kolydas
            Nov 16 '18 at 9:11













          • Thank you for your reply. This should work. However, it can not detect when the user has swiped off the app from "recent apps" (That's why I had to put this in the activity's onDestroy method)

            – Mahmoud Masmoudi
            Nov 16 '18 at 13:24











          • I'm sorry i don't know how to help you more :/ I hope you finally find your answer

            – Alex Kolydas
            Nov 16 '18 at 14:45











          • No worries. I appreciate your help :)

            – Mahmoud Masmoudi
            Nov 16 '18 at 15:52

















          I have just tried it and the output is the same. Did you try to kill your app by swiping it off the recent apps while debugging and while your service is running ? Just to see if the debug session is properly stopped

          – Mahmoud Masmoudi
          Nov 16 '18 at 8:57





          I have just tried it and the output is the same. Did you try to kill your app by swiping it off the recent apps while debugging and while your service is running ? Just to see if the debug session is properly stopped

          – Mahmoud Masmoudi
          Nov 16 '18 at 8:57













          @MahmoudMasmoudi You said you've implemented it in onDestroy()? try call this method from inside your service class.Check the updated answer.I hope it helps

          – Alex Kolydas
          Nov 16 '18 at 9:11







          @MahmoudMasmoudi You said you've implemented it in onDestroy()? try call this method from inside your service class.Check the updated answer.I hope it helps

          – Alex Kolydas
          Nov 16 '18 at 9:11















          Thank you for your reply. This should work. However, it can not detect when the user has swiped off the app from "recent apps" (That's why I had to put this in the activity's onDestroy method)

          – Mahmoud Masmoudi
          Nov 16 '18 at 13:24





          Thank you for your reply. This should work. However, it can not detect when the user has swiped off the app from "recent apps" (That's why I had to put this in the activity's onDestroy method)

          – Mahmoud Masmoudi
          Nov 16 '18 at 13:24













          I'm sorry i don't know how to help you more :/ I hope you finally find your answer

          – Alex Kolydas
          Nov 16 '18 at 14:45





          I'm sorry i don't know how to help you more :/ I hope you finally find your answer

          – Alex Kolydas
          Nov 16 '18 at 14:45













          No worries. I appreciate your help :)

          – Mahmoud Masmoudi
          Nov 16 '18 at 15:52





          No worries. I appreciate your help :)

          – Mahmoud Masmoudi
          Nov 16 '18 at 15:52


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334235%2fhow-to-properly-stop-a-foreground-service%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          List item for chat from Array inside array React Native

          Thiostrepton

          Caerphilly