How to run an asynctask every so often?

3

I'm making an application on android. Inside it I have a Google maps object from which I get the latitude and longitude respectively. The problem is that I need to send this data every 3 seconds to a server through the Web Service. However, I can only execute the "execute" method of the asynctask class once. I tried looping in the doInBackground method, but only sending data once. How could I keep sending the data constantly? This is the loop that I made inside the doInBackground

HttpGet get = new HttpGet( servicio + "Longitud="+ String.valueOf(longitud) +"&Latitud="+ String.valueOf(latitud));


        get.setHeader("Content-type","application/json");
        try{

            while (true){
                response =  httpClient.execute(get);
                respuesta = EntityUtils.toString(response.getEntity());
                respJSON = new JSONObject(respuesta);
                estado = respJSON.getString("estado");
                Log.i("ServicioRest","Latitud--> " + String.valueOf(latitud) + " Longitud--> " + String.valueOf(longitud));

                Thread.sleep(3000);
            }
    
asked by Ken 31.07.2016 в 08:52
source

3 answers

5

The correct thing would be to run your Asynctask every 3 seconds with a timerTask, but not implementing a loop in doInBackground ().

final Handler handler = new Handler();
Timer timer = new Timer();

TimerTask task = new TimerTask() {       
    @Override
    public void run() {
        handler.post(new Runnable() {
            public void run() {       
                try {
                     //Ejecuta tu AsyncTask!                                            
                   AsyncTask myTask = new AsyncTask();
                    myTask.execute();
                } catch (Exception e) {
                    Log.e("error", e.getMessage());
                }
            }
        });
    }
};

timer.schedule(task, 0, 3000);  //ejecutar en intervalo de 3 segundos.
    
answered by 31.07.2016 в 09:11
0

The TimerTask would not be good because with the course of the execution of the application it would consume more resources while the app is open, I recommend creating a class that extends the BroadcastReceiver and by using AlarmManager execute your process a simple example would be something like this:

public class BootDeviceReceiver extends BroadcastReceiver{
 @Override
 public void onReceive(Context context, Intent intent) {
    startServiceByAlarm(context);
 }
}

private void startServiceByAlarm(Context context){
     AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

     Intent intent = new Intent(context, AutoExecute.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notificacion.context=context;

        long startTime = System.currentTimeMillis();
        long intervalTime = 3000;

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, intervalTime, pendingIntent);
}

AsyncTask class I recommend to run it within a service such as:

public class AutoExecute extends Service {
 @Override
public int onStartCommand(Intent intent, int flags, int startId) {

   AsyncTask myTask = new AsyncTask();
   myTask.execute();
   return super.onStartCommand(intent, flags, startId);
}

}

This class would be called on the broadcast receiver. I can not remember that the services must be instantiated in the AndroidManifest.xml.

    
answered by 21.07.2018 в 05:12
0

It would be like this:

  • Declare these at the class level:

    Timer timer = new Timer();
    final Handler handler = new Handler();
    
  • Then perform your method

    public void llamar(){
    
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            AsyncTask mytask = new AsyncTask() {
                @Override
                protected Object doInBackground(Object[] objects) {
    
                    new Handler (Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
    
                          aqui mandas a yamar tus metodos
                        }
                    });
    
                    return null;
                }
            };
            mytask.execute();
        }
    };
    timer.schedule(task,0,1500);
    }
    
  • answered by 21.07.2018 в 02:44