Stop a service after MainActivity is closed (EDITED)

后端 未结 3 930
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-26 07:21

I think im not clear at all, i do want the service to persist even if the main activity is destroyed via user action or android system does it, it does it well, but when the app

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-26 07:56

    If the service already running in background then you need to call stopSelf() on same instance of that service . Now as per service life Cycle onCreate() only call once in the lifetime of service . WhereAs onStartCommand get called each time you call startService() with new intent. So what you can do is to pass a flag in intent to stop it .

    Intent BgServiceIntent = new Intent(MainActivity.this, BgScanService.class);
        BgServiceIntent.putExtra("close",true);
        startService(BgServiceIntent);
    

    And in Service .

     @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        boolean shouldClose=intent.getBooleanExtra("close",false);
        if(shouldClose){
            stopSelf();
        } else {
            // Continue to action here
        }
        return START_STICKY;
    }
    

提交回复
热议问题