Update application every 5 seconds

3

Good evening.

I need to make an application that does an HTTP request every 5 seconds and bring the result of the same one that is in Json format.

Well, this part of the requisition and data collection I've already implemented using Retrofit and Gson.

Now I need to know what to use to make this request every 5 seconds and how to keep the application making these requests even after leaving the application or shutting it down.

I implemented the Service and looked like this:

public class MyService extends Service {

private static final String TAG = "pendentesErro";
private static final String TAG_SUCESSO = "pendentes";

String fila = "";
int total = 0;

@Override
public void onCreate() {
    super.onCreate();
    timer = new Timer();
    timer.schedule(timerTask, 2000, 5000);
}

private Timer timer;
private TimerTask timerTask = new TimerTask() {
    @Override
    public void run() {
        total = 0;

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(FilaPendentesService.URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        FilaPendentesService service = retrofit.create(FilaPendentesService.class);
        Call<FilaPendentes> requestPendentes = service.ListPendentes();

        requestPendentes.enqueue(new Callback<FilaPendentes>() {
            @Override
            public void onResponse(Call<FilaPendentes> call, Response<FilaPendentes> response) {
                if (!response.isSuccessful()) {
                    Log.i(TAG, "ERRO: " + response.code());
                } else {
                    FilaPendentes filaPendentes = response.body();

                    for (Pendente p : filaPendentes.Pendentes) {

                        String operadora = String.format("%s: ", p.Operadora);
                        String quantidade = String.format("%s ", p.Quantidade);

                        total = total + Integer.parseInt(p.Quantidade);

                        fila = (operadora + quantidade + "\n\n");

                        Log.i(TAG_SUCESSO, fila + "\n\n");
                    }
                    Log.i(TAG_SUCESSO, "Total: " + String.valueOf(total));
                }
            }

            @Override
            public void onFailure(Call<FilaPendentes> call, Throwable t) {
                Log.e(TAG, "Erro: " + t.getMessage());
            }
        });
    }
};

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

}

Now I wanted to know how to retrieve these values that I'm showing in the log in an Activity.

    
asked by anonymous 30.05.2016 / 01:23

1 answer

6

I suggest not to use threads to schedule the recurring request, after handling the previous request. Something in style:

final int delay = 5000;
final int period = 5000;
final Runnable r = new Runnable() {
    public void run() {
        ... executa a requisição ...
        postDelayed(this, period);
    }
};

postDelayed(r, delay);

You must implement this part of the application as a Service, which can run independently of the Activity (visible part). So the Activity can be closed and the Service keeps running. You can even initially implement the Activity to run and test, but then you must encapsulate it in a Service.

The Android guidelines state that a Service running in the background should show a "sticky" or "sticky" notification, so the user knows that the Service exists (similarly to a music player that keeps an item stuck in the notifications list).

For a service to have a high chance of getting into memory, start it from the Activity using the startForeground method and passing a "sticky" notification as a parameter (documentation: link )

Still, Android has all the freedom to kill a Service that runs in the background. Same with sticky notification. which decreases but does not eliminate the chance of death. There is no better way to ensure that a Service lasts forever.

To compensate for this risk, assuming you really need the service to run all the time, the solution is to register an Alarm, via AlarmManager (documentation link ).

The alarm will only last while the phone is running, but this is easily fixed by creating a "receiver" for the android.intent.action.BOOT_COMPLETED event, which will run when the phone reboots. There you again register the same alarm. Here's a skeleton on how to make this event-code link: link

    
30.05.2016 / 03:43