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

Android专题3——MainThread向WorkerThread通信

Android一般WorkerThread不能改变UI进程(MainThread)

所以需要Handler

点击数据按钮,启动一个线程,模拟从网上获得数据

技术分享

点击以后,过一秒钟后改变TextView内容

技术分享

首先给Button绑定一个监听器,让其创建一个线程

技术分享

这个线程模拟从网络中获得数据

技术分享

Handler定义如何处理

技术分享

技术分享
package com.njulya.testhandler;import android.app.Activity;import android.os.Bundle;import android.os.Handler;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);        button.setOnClickListener(new OnClickListener(){            @Override            public void onClick(View arg0) {                NetworkThread nt = new NetworkThread();                nt.start();            }        });                handler = new Handler(){            @Override            public void handleMessage(Message msg){                String str = (String)msg.obj;                text.setText(str);            }        };    }    private class NetworkThread extends Thread{        @Override        public void run(){            try {                sleep(2*1000);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            Message msg = handler.obtainMessage();            msg.obj = "从网络获得的数据";            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
技术分享
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context=".MainActivity" >    <TextView        android:id="@+id/textId"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />        <Button         android:id="@+id/buttonId"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@id/textId"        android:text="数据"/></RelativeLayout>
View Code

 

Android专题3——MainThread向WorkerThread通信