Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method after a delay in Android

I want to be able to call the following method after a specified delay. In objective c there was something like:

[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5]; 

Is there an equivalent of this method in android with java? For example I need to be able to call a method after 5 seconds.

public void DoSomething() {      //do something here } 
like image 934
aryaxt Avatar asked Jun 18 '10 18:06

aryaxt


People also ask

How do you call a method after a delay?

You can use this for Simplest Solution: new Handler(). postDelayed(new Runnable() { @Override public void run() { //Write your code here } }, 5000); //Timer is in ms here.

How do you call a method in Android?

To call a method in Java, you type the method's name, followed by brackets. This code simply prints “Hello world!” to the screen. Therefore, any time we write helloMethod(); in our code, it will show that message to the screen.

How do you call a method only once on Android?

putBoolean("key",1); //or you can also use editor. putString("key","value"); editor. commit(); After doing so, say for example if user recalls an activity, then you check the value of in the shared prefs and if it is found, then just perform the action you wish to do else, allow the user to continue with the activity.


1 Answers

Kotlin

Handler(Looper.getMainLooper()).postDelayed({     //Do something after 100ms }, 100) 

Java

final Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(new Runnable() {     @Override     public void run() {         //Do something after 100ms     } }, 100); 

like image 199
kontinuity Avatar answered Oct 08 '22 13:10

kontinuity