如何在android中每5秒循环或执行一次函数

我怎么能每5秒在onCreate上循环那个time()函数..帮我在android =)中新手我想在onCreate中每隔5秒执行一次time()函数.

 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

 } 

任何帮助都会被批评..

试着这样做!只需在startTimer方法中替换您的代码.它应该工作..

private Timer timer;
    private TimerTask timerTask;
    private Handler handler = new Handler();

    //To stop timer
   private void stopTimer(){
        if(timer != null){
            timer.cancel();
            timer.purge();
        }
    }

    //To start timer
    private void startTimer(){
        timer = new Timer();
        timerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run(){
                        //your code is here
                    }
                });
            }
        };
        timer.schedule(timerTask, 5000, 5000);
    }

转载注明原文:如何在android中每5秒循环或执行一次函数 - 代码日志