2

My Requirement is

Android application has to send user location details(latitude & longitude) to the server for every one hour(which is configurable).

The approach I followed is using the alarm manager i am invoking my service at configured intervals which will send the location details to server irrespective of whether the application is running.

Is this a good approach?

Rohit
  • 647
  • 14
  • 30

4 Answers4

3

I prefer ScheduledExecutorService, because it is easier for background Tasks.

AlarmManager:

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock.

ScheduledThreadPoolExecutor:

You can use java.util.Timer or ScheduledThreadPoolExecutor (preferred) to schedule an action to occur at regular intervals on a background thread.

You can see complete answer here => Which is Better ScheduledExecutorService or AlarmManager in android? And Here

    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
           // Hit WebService
        }
    }, 0, 1, TimeUnit.HOURS);
Community
  • 1
  • 1
Nadeem Iqbal
  • 2,357
  • 1
  • 28
  • 43
0

Yes, using AlarmManager is a good approach

The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

please refer this https://developer.android.com/training/scheduling/alarms.html

Sam
  • 4,046
  • 8
  • 31
  • 47
0

Android service run on UI thread so you should not execute long running task in it, like sending data to server. The approach you can use is ScheduledThreadPoolExecutor or AlarmManager for scheduling and using asynctask or any other background thread for sending data to servers

anubhav gupta
  • 46
  • 1
  • 3
0

I prefer Timer for repeated tasks.

TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        process();
    }
};

Timer mTimer = new Timer();
mTimer.schedule(timerTask, 0,60*60*60*1000);
Obsidian Phoenix
  • 4,083
  • 1
  • 22
  • 60