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.
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.
– Piovezan
Has some links?
– Luis Ferreira
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
– Piovezan