New one handler in child threads why does the following error be reported?
Java.lang.RuntimeException:
Can ' t create handler inside thread that have not called looper.prepare ()
This is because the handler object is in the same thread as its caller, and the calling thread is blocked if the delay operation is set in handler. Each handler object binds to a Looper object, and each Looper object corresponds to a message queue (MessageQueue). If you do not specify a Looper object to bind to when you create handler, the system defaults to binding the looper of the current thread to the handler.
In the main thread, the Handler object can be created directly using new Handler (), which automatically binds to the Looper object of the main thread, and is created directly in the non-main thread to create the Handler. Because the Android system does not have looper turned on by default in the main thread, the handler object must be bound to the Looper object. In this case, there are two ways to resolve this problem:
Method 1: You must first manually turn on Looper (Looper.prepare ()-->looper.loop ()) in the thread, and then bind it to the handler object;
Final Runnable Runnable = new Runnable () {
@Override
public void Run () {
Perform time-consuming operations
try {
LOG.E ("BM", "runnable thread:" + thread.currentthread (). GetId () + "name:" + Thread.CurrentThread (). GetName ());
Thread.Sleep (2000);
LOG.E ("BM", "performed time-consuming operation ~");
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
};
New Thread () {
public void Run () {
Looper.prepare ();
New Handler (). Post (runnable);//go directly to the new one Handler in the sub-thread
Looper.loop (); In this case, the Runnable object is running in a child thread and can be networked, but the UI cannot be updated
}
}.start ();
Method 2: With Looper.getmainlooper (), obtain the looper of the main thread and bind it to this handler object.
Final Runnable Runnable = new Runnable () {
@Override
public void Run () {
Perform time-consuming operations
try {
LOG.E ("BM", "runnable thread:" + thread.currentthread (). GetId () + "name:" + Thread.CurrentThread (). GetName ());
Thread.Sleep (2000);
LOG.E ("BM", "performed time-consuming operation ~");
} catch (Interruptedexception e) {
E.printstacktrace ();
}
}
};
New Thread () {
public void Run () {
New Handler (Looper.getmainlooper ()). Post (runnable);//go directly to the new one Handler in the sub-thread
In this case, the Runnable object is running in the main thread and cannot be networked, but the UI can be updated
}
}.start ();
Go to child thread new handler error--can ' t create handler inside thread that have not called looper.prepare ()