android 多线程(2)

来源:互联网 发布:微信群淘宝客有危险吗 编辑:程序博客网 时间:2024/06/10 17:24
在主线程中也就是UI线程中默认存在一个Loop对象,所以我们可以借用主线程的Loop对象进行操作,代码如下
public class MainActivity extends ActionBarActivity {    TextView textView;    private Handler mHandler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            textView.setText((String) msg.obj);        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        textView = (TextView) findViewById(R.id.textView);        new Thread(new Runnable() {            @Override            public void run() {<span style="white-space:pre"></span>//在这里我们可以进行一些耗时的操作                String result ="hahdfjkjka";                mHandler.obtainMessage(0,result).sendToTarget();            }        }).start();    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}
在Handler对象在获取message的时候,其实在messageQUence中是保留了一个死循环在这个例子中我只是用了一个handler对象,这种方式实现多线程之间的消息传递,需要调用线程的时候传递主线程的handler对象
0 0
原创粉丝点击