Currently I call it once like this:
hiloconexion = new ObtenerWebService();
try {
hiloconexion.execute(GET, "1").get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
How can I call it every 5 seconds indefinitely?
I tried using the handler as shown below but the activity closes and returns to the main.
final Handler handler = new Handler();
final int delay = 5000;
handler.postDelayed(new Runnable(){
public void run(){
try {
hiloconexion.execute(GET, "1").get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
handler.postDelayed(this, delay);
}
}, delay);
Also in this other way proposed by a partner:
CountDownTimer countDownTimer = new CountDownTimer(2000,2000) {
@Override
public void onTick(long millisUntilFinished) {
hiloconexion = new ObtenerWebService();
try {
hiloconexion.execute(GET, "1");
} catch(Exception e){ Log.e("TAG", e.getMessage());}
}
@Override
public void onFinish() {
this.start();
}
};
countDownTimer.start();
But the activity is also closed without errors.
The class:
public class ObtenerWebService extends AsyncTask<String, Void, String[][]> {
@Override
protected String[][] doInBackground(String... params) {
String cadena = params[0];
URL url = null;
if (params[1] == "1") {
try {
url = new URL(cadena);
//Abrir la conexión
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0" + " (Linux; Android 1.5; es-ES) Ejemplo HTTP");
int respuesta = connection.getResponseCode();
StringBuilder result = new StringBuilder();
if (respuesta == HttpURLConnection.HTTP_OK) {
// preparo la cadena de entrada
InputStream in = new BufferedInputStream(connection.getInputStream());
// la introduzco en un BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
// Paso toda la entrada al StringBuilder
result.append(line);
}
JSONObject respuestaJSON = new JSONObject(result.toString());
String resultJSON = respuestaJSON.getString("estado");
if (resultJSON.equals("1")) {
// estado es el nombre del campo en el JSON
JSONArray infoJSON = respuestaJSON.getJSONArray("items");
for (int i = 0; i < infoJSON.length(); i++) {
items[i][1] = infoJSON.getJSONObject(i).getString("temp");
}
} else if (resultJSON.equals("2")) {}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
return items;
}
@Override
protected void onCancelled(String s[][]) {
super.onCancelled(s);
}
@Override
protected void onPostExecute(String s[][]) {
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}