问题
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...
回答1:
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);
回答2:
Try to do like this ! just replace your code in startTimer method. It should work..
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);
}
回答3:
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (activefragment == null)
{
fragmentTransaction.remove(activefragment);
} else
{
fragmentTransaction.replace(R.id.fragmentContainer, activefragment, activefragment.getTag());
fragmentTransaction.disallowAddToBackStack();
}
fragmentTransaction.commit();
}
};
handler.postDelayed(runnable, timeout);
回答4:
Here's a simple way to do it in Kotlin.
private lateinit var timer: Timer
private val noDelay = 0L
private val everyFiveSeconds = 5000L
override fun onResume() {
super.onResume()
val timerTask = object : TimerTask() {
override fun run() {
runOnUiThread { /* your code here */ }
}
}
timer = Timer()
timer.schedule(timerTask, noDelay, everySecond)
}
override fun onPause() {
super.onPause()
timer.cancel()
timer.purge()
}
来源:https://stackoverflow.com/questions/34880389/how-to-loop-or-execute-a-function-every-5-seconds-on-android