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

前端之家收集整理的这篇文章主要介绍了如何在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);
    }
原文链接:https://www.f2er.com/android/313782.html

猜你在找的Android相关文章