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