Android Handler 主线程 子线程 双向通信(2)

// 在子线程中可以做一些耗时的工作
                        String sMsg = "";
                        sleep(1000);

Message toMain = new Message();

// mMainHandler.obtainMessage();
                        sMsg = String.valueOf(++nClickTimes);
                        toMain.obj = sMsg + "This is "
                                + this.getLooper().getThread().getName()
                                + ".  你发送了消息: \"" + (String) msg.obj + "\"?"
                                + "这是弟" + sMsg + "次 ";

mMainHandler.sendMessage(toMain);
                        Message toChild = new Message();
                        toChild.obj = "over";
                        // mChildHandler.sendMessage(toChild);

Log.i(CHILD_TAG, "Send a message to the main thread - "
                                + (String) toMain.obj);

} catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

};

// 启动子线程消息循环队列
            Looper.loop();

}
    }

// //////////////////////////////////////////////////////////////////////////

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

info = (TextView) findViewById(R.id.info);
        msgBtn = (Button) findViewById(R.id.msgBtn);
        btn1 = (Button) findViewById(R.id.button1);

mMainHandler = new Handler() {

@Override
            public void handleMessage(Message msg) {
                Log.i(TAG, "Got an incoming message from the child thread - "
                        + (String) msg.obj);

// 接收子线程的消息
                info.setText((String) msg.obj + String.valueOf(nClick));
            }

};

child1 = new ChildThread();
        child1.start();

child2 = new ChildThread();
        child2.start();

msgBtn.setOnClickListener(new OnClickListener() {

@Override
            public void onClick(View v) {

if (child1.childHander != null) {

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/pxdyj.html