How to loop or execute a function every 5 seconds on Android

Chong picture Chong · Jan 19, 2016 · Viewed 28k times · Source

How can I loop that time() function on the onCreate every 5 seconds.. help me I'm a newbie in Android =) ... I want to execute time() function in onCreate every 5 seconds.

 public void onCreate(Bundle savedInstanceState) {
 time(); //<-- How can i execute this every 5 seconds.
 }

 private void time() {
new Handler().postDelayed(new Runnable() {

    @Override
    public void run() {
            int success;
         gps = new GPSTracker(AdminMenu.this);
        if(gps.canGetLocation()){
            tmplat=latitude;
            tmplong=longitude;  
           // new InsertUser1().execute();      
        }

        else{
        gps.showSettingsAlert();
        }

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("LATTTTT" + tmplat);
        System.out.println("LONGGGGGGGG" + tmplong);
    } 

}, 5000); // 5 sec

 } 

Any help would be appreciated...

Answer

Christian Stengel picture Christian Stengel · Jan 19, 2016

You could use a handler, given example would call yourfunction() every second

// Init
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
    @Override
    public void run() {
        yourfunction();
        handler.postDelayed(this, 1000);
    }
};

//Start
handler.postDelayed(runnable, 1000);