How can I implement a Timer/TimerTask that executes an AsyncTask? (Android)
I'm trying to perform a task (ie. load data from a text file) asynchronously and repeatedly at specified times (ie. every few seconds, though this rate may change at runtime).
I have done some r开发者_运维百科esearch and decided that this will require either an AsyncTask or a separate Thread. I have decided to use an AsyncTask for simplicity.
I now need to execute this AsyncTask according to a repeating timer schedule. I believe I must make use of a Timer and a TimerTask.
The code below is a simple form of what I am trying to achieve. When I try to run this code using an Android emulator (through the Eclipse IDE) I get the following message: "Sorry! The application has stopped unexpectedly. Please try again."
I would like to know where the problem arises and how I can fix it. Thanks!
public class Sample extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SimpleTimerTask myTimerTask = new SimpleTimerTask();
long delay = 0;
long period = 5000;
Timer myTimer = new Timer();
myTimer.schedule(myTimerTask, delay, period);
}
private class SimpleAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
return null;
}
}
private class SimpleTimerTask extends TimerTask {
public void run() {
new SimpleAsyncTask().execute();
}
}
}
EDIT: Here are the LogCat Messages that seem to be relevant
FATAL EXCEPTION: Timer-0
java.lang.ExceptionInInitializerError
at ...
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at ...
You're making this way harder than it needs to be. The TimerTask
already runs on it's own thread, so you don't need to use an AsyncTask
just put the code you want to run in the TimerTask.run()
method.
There is a serious limitation of using timertask with asynctask if you want to update UI from OnPostExecute method. A timer is run in separate thread, so you have to find a way to start an asynctask from main thread.
精彩评论