How to properly stop a foreground service?

后端 未结 2 1447
逝去的感伤
逝去的感伤 2021-01-12 22:17

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 sto

相关标签:
2条回答
  • 2021-01-12 22:28

    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();
        }
    
    0 讨论(0)
  • 2021-01-12 22:50

    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();
    }
    
    0 讨论(0)
提交回复
热议问题