brescia123
brescia123

Reputation: 517

Android service constantly running and polling

I've to implement a simple application for test purpose with an always running service in background that polls a server every few seconds. I'm aware of GCM but in my case it is impossible to use as I'm in an intranet without Internet connection.

So I need some explanation on which are the best practices: how can I implement the service to do something every few seconds? AlarmManager? Handler?

Thanks!

Upvotes: 0

Views: 1078

Answers (1)

cYrixmorten
cYrixmorten

Reputation: 7108

Here is one method of doing something repeatedly:

private ScheduledExecutorService exec;

private void startExec() {
    shutDownExec();
    exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {
            // starts immediately and is run once every minute
        }
    }, 0, 1, TimeUnit.MINUTES);
}

private void shutDownExec() {
    if (exec != null && !exec.isTerminated()) {
        exec.shutdown();
    }
}

Can of course be wrapped in a Service to make it run as long as the service lives.

Upvotes: 1

Related Questions