24

I need the equivalent code of setTimeOut(call function(),milliseconds); for android.

setTimeOut(call function(),milliseconds);
home
  • 12,468
  • 5
  • 46
  • 54

5 Answers5

22

You probably want to check out TimerTask

Since you brought up this again I'd like to make a different recommendation, which is a Handler. It is simpler to use than a TimerTask as you won't need to explicitely call runOnUiThread as the Handler will be associated with the UI thread so long as it's created on the UI thread or you create it using the main looper in it's constructor. It would work like this:

private Handler mHandler;
Runnable myTask = new Runnable() {
  @Override
  public void run() {
     //do work
     mHandler.postDelayed(this, 1000);
  }
}

@Override
public void onCreate(Bundle savedState) {
  super.onCreate(savedState);
  mHandler = new Handler(Looper.getMainLooper());
}
//just as an example, we'll start the task when the activity is started
@Override
public void onStart() { 
  super.onStart();
  mHandler.postDelayed(myTask, 1000);
}

//at some point in your program you will probably want the handler to stop (in onStop is a good place)
@Override
public void onStop() {
  super.onStop();
  mHandler.removeCallbacks(myTask);
}

There are some things to be aware of with handlers in your activity:

  1. Your activity can be shutdown/non visible while your handler is still running if you don't stop it in onStop (or onPause if you started it in onResume), this will lead to problems if you try to update the UI
  2. If your phone goes into deep sleep the handlers won't fire as often as you have specified. I know this as I've done some extensive testing with bluetooth devices to test connectivity after many hours of operation and I had used handlers along with log prints every time they fired.
  3. If you need this timer to be ongoing I recommend putting it in a service which will last longer than an activity. Register your activity with the service(by implementing an interface defined in the service for communication with the service).
Matt Wolfe
  • 8,924
  • 8
  • 60
  • 77
11

This is the code that i used in my current project. I used TimerTask as Matt said. 60000 is the milisec. = 60 sec. i used it to refresh match scores.

private void refreshTimer() {
        autoUpdate = new Timer();
        autoUpdate.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        adapter = Score.getScoreListAdapter(getApplicationContext());
                        adapter.forceReload();
                        setListAdapter(adapter);
                    }
                });
            }
        }, 0, 60000);
GiantRobot
  • 432
  • 3
  • 6
  • It doesn't work. WHAT means autoUpdate? and runOnUiThread. Minus – l0gg3r Mar 04 '14 at 15:55
  • 3
    Those questions are hardly relevant, l0gg3r. He gave an example of a task being scheduled to run after 60 seconds, on the UI thread. Any Android developer should easily understand the code. – Eran Boudjnah Mar 08 '14 at 22:21
  • One thing, though, @GiantRobot. This example behaves more like setInterval than setTimeout. The changes required to use this code for setTimeout would be: change the order of the values (60000, 0 instead of 0, 60000) and stop the timer in the run() function, so that it only runs once. – Eran Boudjnah Mar 09 '14 at 09:20
2

There is setTimeout() method in underscore-java library.

Code example:

import com.github.underscore.U;
import java.util.function.Supplier;

public class Main {

    public static void main(String[] args) {
        final Integer[] counter = new Integer[] {0};
        Supplier<Void> incr =
                () -> {
                    counter[0]++;
                    return null;
                };
        U.setTimeout(incr, 100);
    }
}

The function will be started in 100 ms with a new thread.

Valentyn Kolesnikov
  • 2,029
  • 1
  • 24
  • 31
1

As a continuation to Valentyn answer using java underscore:

Add dependency to gradle:

dependencies {
    compile group: 'com.github.javadev', name: 'underscore', version: '1.15'
}

Java:

import com.github.underscore.lodash.$;

$.setTimeout(new Function<Void>() {
    public Void apply() {
        // work
        return null;
    }
}, 1000); // 1 second
noamtcohen
  • 4,432
  • 2
  • 20
  • 14
0

More Android-ish way than dealing with Java Thread is to use Android Looper, considering now you have access to Kotlin,

Handler(Looper.getMainLooper()).postDelayed({ /* action */ }, 2000)

Or, the more Kotlin-ish way to to use androidx.core:core-ktx's Kotlin extensions and then,

import androidx.core.os.postDelayed

Handler(Looper.getMainLooper()).postDelayed(2000) {
    // action
}

You can use TimeUnit.SECONDS.toMillis(2) instead 2000.

Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81