Handler的handleMessage()的线程调用问题


public class MainActivity extends Activity {

    private TextView tt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tt = (TextView)findViewById(R.id.tt);
        this.handlerThread.start();
        new Thread() {

            @Override
            public void run() {
                Message msg = Message.obtain();
                if (msg != null) {
                    msg.what = 11;

                }

                //之所以延迟发送消息,而不能是立即发送消息,是因为此时的viewrootImpl还没初始化完成,
                //所以还能在非ui线程修改view
                mH.sendEmptyMessageDelayed(111, 2000);
            }

        }.start();
    }

    private HandlerThread handlerThread= new HandlerThread("chen");
    private Handler mH= new M();
//    private Handler mH= new M(handlerThread.getLooper()); 这样会报错,
//    因为Handler的handleMessage(Message msg)是运行在Handler所绑定的Looper所在的线程中,
//    所以new M(handlerThread.getLooper());是将该handler和handlerThread【非ui线程】绑定在一起
//    ,即Handler的handleMessage(Message msg)【Looper里面回调了handleMessage】是运行在handlerThread线程中,此时如果在handleMessage(Message msg)
//    操作ui就会报错

    class M extends Handler {



        public M() {
            super();
        }

        public M(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
          tt.setText(msg.what + "..." + 
            Thread.currentThread().getName());
        }

    }
}

你可能感兴趣的:(android基础)