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...
You can use a handler, given both example would call startLooping() every 5 second
Kotlin:
//init
val handler = Handler()
val runnable: Runnable = Runnable {
startLooping()
}
private fun startLooping() {
handler.postDelayed(runnable, 5000)
}
//write inside onCreate method
handler.postDelayed(runnable,5000)
Java:
// Init
private Handler handler = new Handler();
private Runnable runnable = new Runnable()
{
@Override
public void run() {
// your work
handler.postDelayed(this, 5000);
}
};
//write inside onCreate method
handler.postDelayed(runnable, 5000);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With