I have been trying to figure out how to make a custom chronometer that is precise down to a hundredth of a second. I have looked at a lot of the other similar questions and decided to try it using a thread and handler.
This is my custom handleMessage method:
public void handleMessage(Message msg) {
String timeText = msg.getData().getString("time");
watch.setText(timeText);
}
The watch object is just a TextView that is initialized in onCreate().
And this is the main chunk of my run method:
while(true) {
long timeElapsed = System.currentTimeMillis() - startTime;
int hundreths = (int)((timeElapsed % 1000) / 10);
int seconds = (int)((timeElapsed % 60000) / 1000);
int minutes = (int)(timeElapsed / 60000);
Bundle bundle = new Bundle();
bundle.putString("time", String.format("d:%02d.%02d", minutes, seconds, hundreths));
Message msg = handler.obtainMessage();
msg.setData(bundle);
handler.handleMessage(msg);
}
I realize that the whole idea behind using a handler is that only the UI thread can update elements on the screen, but I am still getting a CalledFromWrongThreadException with the message that only the original thread that started created the View hierarchy can call methods on it. I am confused as to what exactly I am doing wrong.
I think your error is because you are using handleMessage instead of sendMessage.
A simpler approach might be to use runOnUiThread method and give up the handler.
http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)