All I am looking to do is run some function 5 seconds after the app starts. However i keep getting a "force close" after 5 sec. Is timerTask even the correct function to be using in a situation like this? How about if i want to press a button later in the program, and have an event occur 5 seconds after user presses the button?
package com.timertest;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class timerTest extends Activity {
Timer timer = new Timer();
TextView test;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
test = (TextView)findViewById(R.id.test);
timer.schedule(task, 5000);
}
TimerTask task = new TimerTask() {
@Override
public void run() {
test.setText("task function run");
}
};
}
If you want to execute some code after 5 secs try the following...
A TimerTask will run on a background thread but you're trying to change UI. You want to run your operation on the UI thread instead. Android traditionally uses messages posted to a
Handler
to do this. A Handler will not create a new thread, when used as shown below it will simply attach to the same message queue that your app uses to process other incoming UI events.