Non-periodic background job runs for a long time

时间:2019-03-17 22:42:18

标签: android

I want to do a http server check in my app repeatedly, and Service seems to be my best choice. If server is good, I want to check in 12h interval. If fail (server down or network problem), use a 5min interval for quick detection.

According to most SO question, for periodic task it's better to use an AlarmManager to start it at a fixed rate. It seems not suitable for me.

I want to create a thread in Service:

public void run() {
    while (true) {
        if (serverCheckGood()) {
            Thread.sleep(1000*60*60*12);
        } else {
            Thread.sleep(1000*60*5);
        }
    }
} 

What the drawback of this method? Is it consuming more power?

BTW, if use above thread model, another choice is overriding Application and run the thread in it. It's more easy to access data from different activity. What's the drawback of this way compared to Service?

In MyApplication:

boolean mServerGood = true;
public void run() {
    while (true) {
        if (serverCheckGood()) {
            mServerGood = true;
            Thread.sleep(1000*60*60*12);
        } else {
            mServerGood = false;
            Thread.sleep(1000*60*5);
        }
    }
}

To access data from activity:

boolean serverGood = ((MyApplication) getApplication()).mServerGood;

1 个答案:

答案 0 :(得分:1)

I want to do a http server check in my app repeatedly, and Service seems to be my best choice

That has never been a particularly good choice. Only have a service running when it is actively delivering value to the user. Watching the clock tick is not actively delivering value to the user.

According to most SO question, for periodic task it's better to use an AlarmManager to start it at a fixed rate

That has not been a great choice for a few years, though it is much better than your proposed solution.

What the drawback of this method?

On Android 6.0+, your timing will stop when the device goes into Doze mode, and so your server will never be checked.

On Android 8.0+, unless you make this a foreground service, your service will be stopped entirely after one minute.

And, it is wasting memory. You only need your process to be running when there is work to do.

So, use WorkManager. If not that, use JobScheduler.