Request within a defined time interval

Asked

Viewed 664 times

2

My application should update a list of data coming from the server every 5 minutes. Using Retrofit for Request HTTP, what’s the best way to do that?

3 answers

2

You can use the feature Alarm Android and set how much in how long it should be called.

First you need to create a broadcast receiver which will be called when the alarm is executed:

public class AlarmReceiver extends BroadcastReceiver {

    private static final String TAG = AlarmReceiver.class.getSimpleName();

    public AlarmReceiver() {
    }

    @Override
    public void onReceive(final Context context, Intent intent) {
        Log.d(TAG, "onReceive()");

        // Aqui você coloca o código que deve ser executado a cada X minutos
    }
}

Don’t forget to add the receiver to your file Androidmanifest.xml (within the application markup):

<receiver
    android:name=".AlarmReceiver"
    android:exported="false"></receiver>

Now you need to create a custom class that extends the class Application (if you no longer have it in your app). I recommend you create the alarm within the method onCreate:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 300000, pendingIntent);
    }
}

Now just add the custom class in Androidmanifest.xml:

<application
        android:name=".MyApplication"

Add the permission WAKE_LOCK in the Androidmanifest.xml:

<uses-permission android:name="android.permission.WAKE_LOCK" />

1

A timer is easier to implement:

 private final Timer myTimer = new Timer();

     public class myClass {

     @Override
     public void onResume() {
            ...   
            myTimer.scheduleAtFixedRate(new myTask(), 0, (long) (18000000));  // Tempo em milisegundos.

        } 



        private class myTask extends TimerTask {
            @Override
            public void run() {
                ... execute os procedimentos.
            }
        }

    }   

https://stackoverflow.com/questions/15571169/i-need-help-understanding-the-scheduleatfixedrate-method-of-thetimer-class-in-ja

http://www.iitk.ac.in/esc101/05Aug/tutorial/essential/threads/timer.html

1

There are several ways to do this, before choosing one, it is necessary to know what each one offers us and choose the one that best suits our needs.

The main advantage of Alarm is that it operates outside the context of your application, allowing you to request, even if the application is not running.
However, it may also be the biggest drawback. After starting the Alarm it will make a request every 5 minutes while the device is not off, with the corresponding battery cost and features.

If you only need to update the list while the application is running, do not use a Alarm.

In that situation the use of Timer could be a possible option.
However, the code executed by Timer runs in a background thread, as Retrofit also runs its methods in a Thread own, it makes no sense to use a background thread to run another background thread.
Besides that it would have to solve the problem of the methods onResponse() and onFailure() be executed in the thread created by Timer and not in the Uithread.
On the other hand, the Timer should not be used for time-consuming tasks.

So if you only need to update the list while the application is running, I suggest you use a Handler.

Declare a field to store the reference to Handler

private Handler handler;

In the onCreate() create the Handler and immediately make the requisition:

handler = new Handler();
handler.post(new UpdateData());

To avoid memory Leaks declare the Updatedata class in a separate java file or as a Static Inner class of Activity.

private static final class UpdateData implements Runnable{
   @Override
   public void run() {
      //Faça aqui a requisição via Retrofit
      .....

      //agenda nova requisição daqui a 5 minutos
      handler.postDelayed(this, 5*60*1000);
   }
}

In the method onDestroy() remove the request for new requests:

@Override
protected void onDestroy(){
    super.onDestroy();
    handler.removeCallbacksAndMessages(null);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.