Android - Best Practice for Periodic Service

I want to implement a service that its task is to periodically retrieve updates from the Internet. I know that there are several ways to achieve this. I list 2 of them. Please tell me which is more efficient and in practice which way is more common. thanks in advance

1. Implement an infinite while (true) loop inside a separate thread, and then run this thread in the service onStartCommand. pseudo code:

class Updater extends Service {
    ...
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){

                    // fetching update...

                    Thread.sleep(FOR_A_WHILE);
                }
            }
        }).start();
    }
    ...
}

2.Schedule AlarmManagerto run periodically IntentService, which retrieves the update

+2
source share
2 answers

while (true) , onStartCommand.

ScheduledExecutorService.

, , , .

- , .

- Thread.sleep() ScheduledExecutorService - : " - N , , ".

: " - N , (, , ), , ".

, , . .

+5

. , - ( ), , , iupdate, , , ( ), , , -

+2

Source: https://habr.com/ru/post/1623433/


All Articles