2 Steps to use Looper.prepare() and Looper.loop() in Android



In article “2 Steps to solve problem:Can’t create handler inside thread that has not called Looper.prepare() in Android“, We know a truth: a toast can not be run in no-ui thread in android, if you should realize it you should use Looper.prepare().

How to use Looper.prepare() you may ask me, you can use it like follow steps:

Step 1: Effect of Loop.prepare() and Looper.loop()

In Anroid Looper you can get some very useful information on Loop.prepare, however, if you think that is too hard to you ,you can understand it like this.

Loop.prepare and Looper.loop() can create a ui thread, then you can run some ui process between them.

Step 2: Example of using Loop.prepare() and Looper.loop()

To understand how to use Loop.prepare() and Looper.loop(), you can read example below.

We know we can not show a toast in a no-ui thread in android, so if you run this code below, you will find a toast will be showed in ui thread.


public class TestActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState){
 super.onCreate(savedInstanceState);
 this.setContentView(R.layout.test);
 Button btn = (Button) this.findViewById(R.id.back_id);
 btn.setOnClickListener(new OnClickListener() {
 public void onClick(View v) {
 new Thread(new Runnable(){

@Override
 public void run() {
 // TODO Auto-generated method stub
 Looper.prepare();
 showToast("Toast run in sub thread");
 Looper.loop();
 }

 }).start();
 }
 });
 showToast("Toast run in UI thread");
 }
 private void showToast(String msg) {
 Toast.makeText(TestActivity.this, msg, Toast.LENGTH_LONG).show();
 }
}

However, if you plan to show it in a no-ui thread,you must use key code:


Looper.prepare();
showToast("Toast run in sub thread");
Looper.loop();

Then we will create a ui thread, which can show my toast.

taost run in sub thread

Tips and Warnings:

(1) code above if you remove Loop.prepare() and Looper.loop(), this application will break down and stop.