首页 > 代码库 > 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-解决在主线程之外的线程不能访问界面组件的问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。