I need the equivalent code of setTimeOut(call function(),milliseconds);
for android.
setTimeOut(call function(),milliseconds);
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);
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:
There is setTimeout() method in underscore-java library. I am the maintainer of the project.
Code example:
import com.github.underscore.lodash.U;
import com.github.underscore.Function;
public class Main {
public static void main(String[] args) {
final Integer[] counter = new Integer[] {0};
Function<Void> incr = new Function<Void>() { public Void apply() {
counter[0]++; return null; } };
U.setTimeout(incr, 100);
}
}
The function will be started in 100ms with a new thread.
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