I have this Intent service:
public class MyIntentService extends IntentService {
public static final String TAG = "MyIntentService";
private TimerTask timerTask;
private Timer timer;
public MyIntentService() {
super("MyIntentService");
}
public static void startService(Context context) {
Log.d(TAG, "startService: ");
Intent intent = new Intent(context, MyIntentService.class);
context.startService(intent);
}
@Override
public void onCreate(){
super.onCreate();
Log.d(TAG, "onCreate: ");
timer = new Timer();
timerTask = new TimerTask() {
@Override
public void run() {
Log.d(TAG, "run: service");
}
};
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
timer.cancel();
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "onHandleIntent: ");
timer.scheduleAtFixedRate(timerTask, 0, 5000);
}
}
When I called function startService from activity with MyIntentService.startService(getApplicationContext());
, service is started but immediatelly ended.
2022-05-04 15:24:58.449 6809-6809/myapplication D/MyIntentService: startService:
2022-05-04 15:24:58.465 6809-6809/myapplication D/MyIntentService: onCreate:
2022-05-04 15:24:58.466 6809-6838/myapplication D/MyIntentService: onHandleIntent:
2022-05-04 15:24:58.467 6809-6839/myapplication D/MyIntentService: run: service
2022-05-04 15:24:58.467 6809-6809/myapplication D/MyIntentService: onDestroy:
When I remove timer.cancel(); from destructor, timer continue to work, but service looks dead. I thaught that service is ended by calling stop service - so why is ended in this case? Thank you very much D