I need to understand about the Looper. Looper will consult appropiate handler to to send and process Message and Runnable objects associated with a thread's MessageQueue.
By default, a thread does not have a message loop associated with it, hence doesn’t have a Looper either. To create a Looper for a thread and dedicate that thread to process messages serially from a message loop, you can use the Looper class.
The following is my code I don't invoke Looper explicitly
Thread background2 = new Thread(new Runnable() {
@Override
public void run() {
for ( int i = 0; i < 5; i++) {
final int v =i;
try { Thread.sleep(1000);
handler.post(new Runnable() {
@Override
public void run() {
txt.setText(txt.getText() + "Thread 2 current i : " + String.valueOf(v) +System.getProperty("line.separator"));
}
});
} catch (Exception e) {
Log.v("Error", e.toString());
}
}
}
});
Does it mean that the task/runnable is not put in the queue? what's the difference of above code with this
Thread background3 = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
for ( int i = 0; i < 5; i++) {
final int v =i;
try { Thread.sleep(1000);
handler.post(new Runnable() {
@Override
public void run() {
txt.setText(txt.getText()+ "Thread 3 set : " + String.valueOf(v) +System.getProperty("line.separator"));
}
});
} catch (Exception e) {
Log.v("Error", e.toString());
}
}
Looper.loop();
}
});
both of them accessing a same handler. They both work fine.