首页 > 代码库 > Android-解决在主线程之外的线程不能访问界面组件的问题

Android-解决在主线程之外的线程不能访问界面组件的问题

报的异常错误: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

 

解决方法:使用Handle来处理来自线程的消息。

 

package com.example.net_simplenet;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.Socket;import java.net.UnknownHostException;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {    TextView show;    Button btn;    //处理线程消息的handler    Handler handler;    //消息类型    final static int MSG_TYPE = 0x123;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        show = (TextView) findViewById(R.id.show);        btn = (Button) findViewById(R.id.button1);        handler = new Handler()        {            @Override            public void handleMessage(Message msg) {                // TODO Auto-generated method stub                //super.handleMessage(msg);                if (msg.what == MSG_TYPE) {                    show.setText(msg.obj.toString());                }            }        };        btn.setOnClickListener(new OnClickListener() {                        @Override            public void onClick(View v) {                // TODO Auto-generated method stub                new Thread()                {                    @Override                    public void run() {                        try {                            Socket socket = new Socket("192.168.14.100", 30000);                            BufferedReader br = new BufferedReader(                                    new InputStreamReader(socket.getInputStream()));                            String line = br.readLine();                            Message msg = new Message();                            msg.what = MSG_TYPE;                            msg.obj = line;                            handler.sendMessage(msg);                            br.close();                            socket.close();                        } catch (UnknownHostException e) {                            // TODO Auto-generated catch block                            e.printStackTrace();                        } catch (IOException e) {                            // TODO Auto-generated catch block                            e.printStackTrace();                        }                    };                }.start();            }        });            }}

 

Android-解决在主线程之外的线程不能访问界面组件的问题