Looper thread的应用实例
创建一个有looper的thread,然后由主线程向其发信息。
public class TestLooperActivity extends Activity { Runnable ra; TextView tv; LooperThread lt; Context context; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); context = this; Button btn = (Button)this.findViewById(R.id.button1); lt = new LooperThread(); btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub lt.mHandler.sendEmptyMessage(10); } }); lt.start(); } class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here if (msg.what == 10) { Toast.makeText(context, "Looper worked!!", Toast.LENGTH_LONG).show(); } } }; Looper.loop(); } } }
------------------------------------
转载自:http://stackoverflow.com/questions/4838207/how-to-create-a-looper-thread-then-send-it-a-message-immediately
Eventual solution (minus error checking), thanks to CommonsWare:
class Worker extends HandlerThread { // ... public synchronized void waitUntilReady() { d_handler = new Handler(getLooper(), d_messageHandler); } }
And from the main thread:
Worker worker = new Worker(); worker.start(); worker.waitUntilReady(); // <- ADDED worker.handler.sendMessage(...);
This works thanks to the semantics of HandlerThread.getLooper() which blocks until the looper has been initialized.
Incidentally, this is similar to my solution #1 above, since the HandlerThread is implemented roughly as follows (gotta love open source):
public void run() { Looper.prepare(); synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); } Looper.loop(); }
public Looper getLooper() { synchronized (this) { while (mLooper == null) { try { wait(); } catch (InterruptedException e) { } } } return mLooper; }
The key difference is that it doesn't check whether the worker thread is running, but that it has actually created a looper; and the way to do so is to store the looper in a private field. Nice!