Home > Software engineering >  Android intent service is finished after start
Android intent service is finished after start

Time:05-05

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

CodePudding user response:

Once onHandleIntent() returns, your service will be shut down. IntentService is not only deprecated, but it is not suitable for your use case.

Use a regular Service as a foreground service if you feel that you need to do work every five seconds (and be prepared for problems, since Google, device manufacturers, and users all do not like apps that try to do work every five seconds and all will take steps to stop you, to save on battery life).

  • Related