Service stop's whenever app is killed

后端 未结 3 602
渐次进展
渐次进展 2020-12-17 03:13

START_STICKY don\'t work in my device whenever i kill my app then service don\'t start again, My device name is Redmi Note 3 Pro, but whenever i run same app in android emul

3条回答
  •  时光说笑
    2020-12-17 03:49

    Code might help you in HourlyService class onStartCommand method returns START_STICKY

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    

    Inside Activity

     private HourlyService mHourlyService;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            LocalBinder binder = (LocalBinder) iBinder;
            mHourlyService = binder.getService();
            mBound = true;
        }
    
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
        }
    };
    
    @Override
    protected void onStart() {
        super.onStart();
        // Bind to LocalService
        Intent intent = new Intent(this, HourlyService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        unbindService(mServiceConnection);
        mBound = false;
    }
    

提交回复
热议问题