Update application every 5 seconds

Asked

Viewed 933 times

3

Good night.

I need to make an application that makes an http request every 5 seconds and brings the same result that is in Json format.

Well, this part of requesting and obtaining the data I’ve 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 doing these requests even after exiting the application or terminating it.

I implemented the Service and stayed 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 recover these values that I am showing in the log in an Activity.

  • 2

    I hope that these requests every 5 seconds do not last long, because they end up with the battery. Even every 1 minute is over. If you need to monitor the status of a server, use push Notifications.

  • Has some links?

  • 1

    Firebase Cloud Messaging, former GCM: https://firebase.google.com/docs/cloud-messaging/ Understanding battery consumption: https://developer.android.com/training/efficient-downloads/efficient-network-access.html?hl=pt-br

1 answer

6


I suggest nay use threads to schedule the periodic request, after having handled 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 should implement this part of the application as a Service, which can run independently of Activity (visible part). Thus the Activity can be closed and the Service continues running. You can even initially implement in Activity to make it work and test, but then you must encapsulate in a Service.

The Android guidelines determine that a Service that runs in the background should show a notification "sticky" or "Sticky" (which cannot be removed), so that the user knows that there is a Service (analogous to a music player who keeps an item stuck in the notification list).

For a service to have a great chance of staying in memory, start it from Activity using the startForeground method and passing a "Sticky" notification as a parameter (documentation: https://developer.android.com/reference/android/app/Service.html#startForeground(int, android.app.Notification) )

Still, the Android has all the freedom to kill a Service that runs in the background. Even with Sticky notification. that decreases but does not eliminate the chance of death. Save better judgment there is no way to ensure that a Service lasts forever.

To compensate for this risk, assuming you really need the service to run at all times, the solution is to register an Alarm, via Alarmmanager (documentation https://developer.android.com/training/scheduling/alarms.html).

The alarm will only last while the phone is running, but this is easily fixed by creating a "receiver" for the android event.intent.action.BOOT_COMPLETED, which will run when the phone restarts. There you return to register the same alarm. Follows a skeleton of how to make this connection between event and code: http://www.learn-android-easily.com/2013/07/bootcompleted-broadcastreceiver-in.html

Browser other questions tagged

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