Reputation: 3229
How can this be done in android?
public final Timer timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Do task here
}
});
I need to be able to call timer.start(); from the Activity that timer is in.
Upvotes: 3
Views: 26763
Reputation: 495
Try something like this:
// this will run when timer elapses
TimerTask myTimerTask = new TimerTask() {
@Override
public void run() {
// ...
}
};
// new timer
Timer timer = new Timer();
// schedule timer
timer.schedule(myTimerTask, delayInMs);
If you want task to be done in activity's main thread, modify it like this:
// get a handler (call from main thread)
final Handler handler = new Handler();
// this will run when timer elapses
TimerTask myTimerTask = new TimerTask() {
@Override
public void run() {
// post a runnable to the handler
handler.post(new Runnable() {
@Override
public void run() {
// ...
}
});
}
};
// new timer
Timer timer = new Timer();
// schedule timer
timer.schedule(myTimerTask, delayInMs);
Upvotes: 4
Reputation: 2129
In most cases it is much better to use a Handler instead of Timer. Handler is capable of sending delayed messages. Benefits of using Handler are:
Example:
class MyActivity extends Activity {
private static final int DISPLAY_DATA = 1;
// this handler will receive a delayed message
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Do task here
if (msg.what == DISPLAY_DATA) displayData();
}
};
@Override
void onCreate(Bundle b) {
//this will post a message to the mHandler, which mHandler will get
//after 5 seconds
mHandler.sendEmptyMessageDelayed(DISPLAY_DATA, 5000);
}
}
Upvotes: 9
Reputation: 13129
I have answered this in another question.
I would avoid the TimerTask, if you fire a lot of them off, they are not only difficult to manage but bad for performance.
I would recommend a Handler
for pretty much any Time based task these days.
Upvotes: 0