如何在Android上每5秒循环或执行一个功能 [英] How to loop or execute a function every 5 seconds on Android
本文介绍了如何在Android上每5秒循环或执行一个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何每5秒在onCreate上循环一次time()函数..帮我,我是Android新手=)...我想每5秒在onCreate上执行一次time()函数.>
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...
推荐答案
您可以使用处理程序,给出的示例将每秒调用yourfunction()
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);
这篇关于如何在Android上每5秒循环或执行一个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文