I have this what seems like a very tedious task of rescheduling a Timer along with TimerTask to enable my service/ongoing process to execute at different times…i have tried searching many forums including this example which seems to have worked for this person but when i try the same code in my service, i get the following error:
03-04 14:21:41.204: E/AndroidRuntime(336): FATAL EXCEPTION: Timer-0
03-04 14:21:41.204: E/AndroidRuntime(336): java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()
Does anyone know what this error means, and what can be a possible solution? from what i researched online about this error: it usually happens when im trying to do UI changes, on a non-UI thread…in my case, all i do is send a notification and then call a reScheduleTimer function like in that example…
any input is appreciated…
EDIT:
here is the code where its blowing up:
public void reScheduleTimer(long duration) {
Log.v(TAG, "Inside reScheduleTimer");
timer.cancel();
timer = new Timer("profileSwitcherTimer", true);
timerTask = new MyTimerTask(); <----
timer.schedule(timerTask, duration);
}
here is the MyTimerTask class:
public class MyTimerTask extends TimerTask{
private Handler updateUI = new Handler(){
public void dispatchMessage(Message msg) {
Toast.makeText(getApplicationContext(), "Timer Ran", Toast.LENGTH_LONG).show();
}
}
public void run() {
....code that i want execute
showNotification();
reScheduleTimer(60000);
}
}
You’re creating the Handler on a thread that does not have a message loop. As the
Looperdocumentation says:One way to fix this would be to explicitly bind you Handler instance to a particular Looper, by using the Handler constructor that takes one. The easiest would be to just use the main looper for the application; you can get it thourgh the static
Looper.getMainLooper()method. The drawback is that this will bind your handler to the UI thread, which by itself is not that bad, as long as you don’t do too long operations on it; otherwise your UI will become unresponsive.