Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop or execute a function every 5 seconds on Android

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...

like image 478
Chong Avatar asked Jan 19 '16 15:01

Chong


2 Answers

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);
like image 177
Rahul Avatar answered Sep 20 '22 17:09

Rahul


 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);
like image 33
Behzad F94 Avatar answered Sep 21 '22 17:09

Behzad F94