Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call method after every 20 seconds in Android

I want to write an Android application which when opened call a method after 20 seconds then auto call method every 10 seconds.

Any thoughts on how to proceed?

like image 733
Jawed Warsi Avatar asked Jun 26 '15 12:06

Jawed Warsi


People also ask

How do I make my Android run every 10 seconds?

This example demonstrates how do I run a method every 10 seconds in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do you call a function repeatedly after a fixed time interval in Android?

You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.

How do you call a method only once on Android?

putBoolean("key",1); //or you can also use editor. putString("key","value"); editor. commit();


3 Answers

You could do it with a single Handler like this:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
   @Override
   public void run() {
       //Do something after 20 seconds
   }
}, 20000);  //the time is in miliseconds

And to repeate the same every 10 seconds you could add the following line in the same method

handler.postDelayed(this, 10000);

Like this:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
   @Override
   public void run() {
       //Do something after 20 seconds
       handler.postDelayed(this, 10000);
   }
}, 20000);  //the time is in miliseconds
like image 118
Gabriella Angelova Avatar answered Nov 04 '22 01:11

Gabriella Angelova


Please check the below code.

new Timer().scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
 // Enter your code
}
            }, 0, 20000);//put here time 1000 milliseconds=1 second

Hope this code will help you.

like image 34
Vatsal Shah Avatar answered Nov 04 '22 00:11

Vatsal Shah


CountDownTimer cdt;

cdt = new CountDownTimer(timeint * 60 * 1000, 1000) {
    @Override
    public void onTick(long millisUntilFinished) {          
        Log.i(TAG, millisUntilFinished " millis left");
    }

    @Override
    public void onFinish() {
        Log.i(TAG, "Timer finished");
    }
};

cdt.start();
like image 45
preethi Avatar answered Nov 04 '22 00:11

preethi