首页 > 代码库 > Android专题4——MainThread向WorkerThread通信

Android专题4——MainThread向WorkerThread通信

WorderThread这里是接受数据

所以创建Handler对象以及对数据的处理方法要放在这里

 

 

首先创建WorkerThread线程并在其中创建Handler对象以及重写handlerMessage方法

技术分享

当点击Button,向WorkerThread发送数据

技术分享

技术分享
package com.njulya.testhandler;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {    private Handler handler;    private TextView text ;    private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                text = (TextView)findViewById(R.id.textId);        button = (Button)findViewById(R.id.buttonId);                Thread td = new Thread(){            @Override            public void run(){                Looper.prepare();                handler = new Handler(){                    @Override                    public void handleMessage(Message msg){                        String str = (String)msg.obj;                        System.out.println(str);                    }                };                Looper.loop();            }        };        td.start();                button.setOnClickListener(new OnClickListener(){            @Override            public void onClick(View arg0) {                Message msg = handler.obtainMessage();                msg.obj = "MainThread发送的数据";                handler.sendMessage(msg);            }        });    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    }
View Code

 

Android专题4——MainThread向WorkerThread通信