1. 程式人生 > >2017.12.18 Android開發之消息隊列(實現子線程修改UI組件)

2017.12.18 Android開發之消息隊列(實現子線程修改UI組件)

nds ace text read exce xtend prot ktr sta

1.界面布局,以及組件初始化:

技術分享圖片

組件初始化:

 private Button button;
    private Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(
new ButtonListener()); handler=new FirstHandler(); }

2.消息隊列的使用:

    class ButtonListener implements View.OnClickListener{  //設置監聽器,使得每點一次按鈕生成一次消息
        @Override
        public void onClick(View view) {
            Message msg=handler.obtainMessage();
            msg.what=8
; //msg的其中一個參數,可以設置很多msg的參數 handler.sendMessage(msg); //把消息扔出去 } } class FirstHandler extends Handler{ @Override public void handleMessage(Message msg) { //處理消息,傳一個消息體進來,理解為一個對象,可以是字符串,int型之類的 int what=msg.what; System.
out.println("數據what是:"+what); super.handleMessage(msg); } }

3.通過消息隊列來修改主線程的文字:

 class MyHandler extends Handler{
    @Override
    public void handleMessage(Message msg) {
        System.out.println("這是來自MyHandler的信息:"+Thread.currentThread().getName());
        String s=(String)msg.obj;
        textview.setText(s);
        super.handleMessage(msg);
    }
}
    class ButtonListener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            Thread thread=new NetWorkThread();
            thread.start();
        }
    }

    class NetWorkThread extends Thread{
        @Override
        public void run() {
            System.out.println("來自NetWorkThread的信息:"+Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String s="有理想的愛國青年";
            Message msg=handler.obtainMessage();
            msg.obj=s;
            handler.sendMessage(msg);

            super.run();
        }
    }

技術分享圖片

2017.12.18 Android開發之消息隊列(實現子線程修改UI組件)