简体   繁体   中英

Android background service timer doesn't work properly

I have an android app. This app sends location information to the server every 15 seconds. I have a background service and timer. I saved to file app logs. When I examine the logs, I saw the timer doesn't work properly sometimes. The problem is happening only when the app went background. What is the best practice background tasks android?

Timer timer = new Timer();
timer.schedule(new mainTask(), 0, 15000);

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;
}

Thread call timestamp logs.

//for example, thread didn't work 2 minutes. 
17:19:35.627
17:21:31.201
thread didn't work 4 minutes.
17:25:23.573 
thread didn't work 4 minutes.
17:29:35.345

Newer versions of Android put background execution limit and you might face this kind of problems while you are trying to run tasks in the background.

You might consider using a JobScheduler which might help you in this case. Here 'sa good implementation tutorial.

Please try to use Handler instead of Timer .

private Handler handlerUpdateLocation;

Also Start your Handle inside onStartCommand() method.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    if (handlerUpdateLocation == null) {
        handlerUpdateLocation = new Handler();
        handlerUpdateLocation.post(runnableUpdateLocation);
    }

    return START_STICKY;
}

Use this runnable to execute code at every 15 seconds.

private Runnable runnableUpdateLocation = new Runnable() {

    @Override
    public void run() {
        // TODO: You can send location here
        handlerUpdateLocation.postDelayed(this, 15000);
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM