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.