Reputation: 47
I have written a service with timer to do something periodically but when I stop service service from mainActivity if my service is in middle of their task it's continue to finish and after that stop it and the same issue when i want to close application that call OnDestroy on Main Activity service work and after finish their task don't start again. My Question is how can Force stop service when i want to exit from my app? this is my service code
public class MyTimerService extends Service{
private static int counter = 0;
private Timer timer = new Timer();
private int INTERVAL;
@Override
public IBinder onBind(Intent i) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
INTERVAL = intent.getIntExtra("time", 500);
repaet();
return START_NOT_STICKY;
}
private void repaet() {
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Log.i("Saeed", String.valueOf(++counter));
}
}, 0, INTERVAL);
}
@Override
public void onDestroy() {
Toast.makeText(this, "Stop Service", Toast.LENGTH_LONG).show();
if(timer!=null){
timer.cancel();
}
stopSelf();
super.onDestroy();
}
}
Upvotes: 0
Views: 1095
Reputation: 180
Have you tried to manually stop your service inside onDestroy() by using this stopService()?
Upvotes: 1