消息通道looper

  1. FirstAcitvity

public class FirstActivity extends AppCompatActivity {
    private Button but = null;
    private static final int SET = 1;         //what操作码
    private TextView info  = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_main);
        this.info = (TextView)findViewById(R.id.info);
        this.but = (Button)findViewById(R.id.but);
        this.but.setOnClickListener(new OnClickListenterImpl());

    }


    private class OnClickListenterImpl implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.but:
                    Looper looper = Looper.myLooper();      //取得当前线程
                    MyHandler myHandler = new MyHandler(looper);      //构造一个handler
                    myHandler.removeMessages(0);          //清空所有的消息队列
                    String data = "hello,world";
                    Message msg = myHandler.obtainMessage(SET,1,1,data);     //发送消息
                    myHandler.sendMessage(msg);
                    break;
            }
        }
    }
    private class MyHandler extends android.os.Handler {
        public MyHandler(Looper looper) {           //接收handler
            super(looper);      //调用父类构造
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    FirstActivity.this.info.setText(msg.obj.toString());
            }
        }
    }
}
2. activity_main.xml
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/info"/>
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/but"
    android:text="启动"
    android:layout_below="@+id/info"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="76dp" />


你可能感兴趣的:(线程,android,textview)