How to properly stop a foreground service?

后端 未结 2 1446
逝去的感伤
逝去的感伤 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: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();
    }
    

提交回复
热议问题