Scheduling recurring task in Android

前端 未结 5 2261
南方客
南方客 2020-11-22 09:12

I\'m designing an app that has a recurring task of sending presence to a dedicated server as long as the app is in foreground.

In my searches across the web I saw a

5条回答
  •  温柔的废话
    2020-11-22 09:47

    Timer

    As mentioned on the javadocs you are better off using a ScheduledThreadPoolExecutor.

    ScheduledThreadPoolExecutor

    Use this class when your use case requires multiple worker threads and the sleep interval is small. How small ? Well, I'd say about 15 minutes. The AlarmManager starts schedule intervals at this time and it seems to suggest that for smaller sleep intervals this class can be used. I do not have data to back the last statement. It is a hunch.

    Service

    Your service can be closed any time by the VM. Do not use services for recurring tasks. A recurring task can start a service, which is another matter entirely.

    BroadcastReciever with AlarmManager

    For longer sleep intervals (>15 minutes), this is the way to go. AlarmManager already has constants ( AlarmManager.INTERVAL_DAY ) suggesting that it can trigger tasks several days after it has initially been scheduled. It can also wake up the CPU to run your code.

    You should use one of those solutions based on your timing and worker thread needs.

提交回复
热议问题