Search code examples
androidbackground-process

Android pool data sending using a service


I have an app which will send 100 data to a web api. right now I am using a service which will run through a scheduler. My problem is that scheduler is starting again before the data sending completes. How can I pause my scheduler till my process completes.

 public class PollReceiver extends BroadcastReceiver {
 private static final int PERIOD=100000;
  @Override
  public void onReceive(Context ctxt, Intent i)
  {
scheduleAlarms(ctxt);
  }
  static void scheduleAlarms(Context ctxt)
   {
AlarmManager mgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
    Intent i=new Intent(ctxt, ScheduledService.class);
     PendingIntent pi=PendingIntent.getService(ctxt, 0, i, 0);
     mgr.setRepeating(AlarmManager.ELAPSED_REALTIME,SystemClock.elapsedRealtime() +     PERIOD, PERIOD, pi);
   }
     }

Schedule Reciever

    public ScheduledService()
    {
    super("ScheduledService");
}

@Override
protected void onHandleIntent(Intent intent) 
     {
    if (isOnline())
            {
        //Process Starts 
    }
}

Solution

  • Set a new schedule after sending completes. After first scedule is set, the next schedule is set by the service itself:

    public class PollReceiver extends BroadcastReceiver {
        private static final int PERIOD=100000;
    
        @Override
        public void onReceive(Context ctxt, Intent i)
        {
                scheduleNextAlarm(ctxt);
        }
    
        static void scheduleNextAlarm(Context c)
        {
            AlarmManager mgr=(AlarmManager)c.getSystemService(Context.ALARM_SERVICE);
            Intent i = new Intent(c, ScheduledService.class);
            PendingIntent pi=PendingIntent.getService(c, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
            mgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + PERIOD, pi);
        }
    
        public static class ScheduledService extends IntentService{
    
            public ScheduledService() {
                super("scheduled_service");
            }
    
    
            @Override
            protected void onHandleIntent(Intent intent) {
                try{
                // do your work
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    scheduleNextAlarm(this);
                }
            }
        }
    }