Batz Pogi Batz Pogi - 2 months ago 15
Android Question

Button to trigger every 5 seconds

My app needs tracking of real time so I need a button that needs to trigger every 5 seconds but I have no idea how to do it. Can you teach me how?

I want that in every 5 seconds that

AsyncTask
will be triggered.

btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HashMap postLoc = new HashMap();
postLoc.put("txtLat", tvLat.getText().toString());
postLoc.put("txtLng", tvLong.getText().toString());
postLoc.put("txtOwner", pref.getString("username","").toString());

PostResponseAsyncTask taskLoc = new PostResponseAsyncTask(getActivity(), postLoc,false, new AsyncResponse() {
@Override
public void processFinish(String s) {
Log.d(TAG, tvLat.getText().toString());
Log.d(TAG, tvLong.getText().toString());
Intent i = new Intent(getActivity(),GPS_Service.class);
getActivity().startService(i);
}
});

taskLoc.execute("http://carkila.esy.es/carkila/locationUpdate.php");
}
});

Answer

I think this code might be useful to trigger the code every 5 second

 Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
 @Override
public void onCreate() {
    super.onCreate();             
    startTimer();
}

public void startTimer() {
    //set a new Timer
    timer = new Timer();

    //initialize the TimerTask's job
    initializeTimerTask();

    timer.schedule(timerTask, 0, 5000); 
}

public void initializeTimerTask() {
    timerTask = new TimerTask() {
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                   //code to run after every 5 seconds
                }
            });
        }
    };
}