Search code examples
javaandroidandroid-service

how to force stop android service programmatically


I make tow buttons one to start service and other to stop it when I press stop button notify me service is stopped but actually it still working in the background i use timer in my onStartCommand() method repeat every second is it the reason..? and how to force stop service immediately.

public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(getApplicationContext(),"start..",Toast.LENGTH_SHORT).show();
    new Timer().scheduleAtFixedRate(new TimerTask() {

        private Handler handler = new Handler(){
            @Override
            public void dispatchMessage(Message msg) {
                Toast.makeText(getApplicationContext(),""+(counter+=1),Toast.LENGTH_SHORT).show();
            }
        };
        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }
    },0,1000);


    return START_STICKY;
}

`

and my buttons action :-

public void btnStart(View view){

    startService(new Intent(MainActivity.this,MyService.class));

}
public void btnStop(View view){

   stopService(new Intent(MainActivity.this,MyService.class));
}

i found answer ..! the answer is must cancel timer and timerTask in onDestroy method


Solution

  • Here's a simplified description of how to stop services :

    stopSelf() is used to always stop the current service.

    stopSelf(int startId) is also used to stop the current service, but only if startId was the ID specified the last time the service was started.

    stopService(Intent service) is used to stop services, but from outside the service to be stopped.

    visit this link for more details

    please replace

    return START_STICKY;
    

    by

    return START_NOT_STICKY;
    

    Difference:

    START_STICKY

    the system will try to re-create your service after it is killed

    START_NOT_STICKY

    the system will not try to re-create your service after it is killed