现在的位置: 首页 > 综合 > 正文

关于“Only the original thread that created a view hierarchy can touch its views.”异常的处理

2017年12月01日 ⁄ 综合 ⁄ 共 2154字 ⁄ 字号 评论关闭

原因:android中相关的view和控件不是线程安全的,我们必须单独做处理。这里借此引出Handler的使用。

Handler的官方描述:


A Handler allows you to send and process
Message
and Runnable objects associated with a thread's MessageQueue.
Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables
to that message queue and execute them as they come out of the message queue


Handler的使用场合:

1、
to schedule messages and runnables to be executed as some point in the future;

      安排messages和runnables在将来的某个时间点执行。

2、 to enqueue an action to be performed on a different thread than your own.

      将action入队以备在一个不同的线程中执行。即可以实现线程间通信。比如当你创建子线程时,你可以再你的子线程中拿到父线程中创建的Handler对象,就可以通过该对象向父线程的消息队列发送消息了。由于Android要求在UI线程中更新界面,因此,可以通过该方法在其它线程中更新界面。  


通过Handler更新UI实例:

步骤:

1、创建Handler对象(此处创建于主线程中便于更新UI)。

2、构建Runnable对象,在Runnable中更新界面。

3、在子线程的run方法中向UI线程post,runnable对象来更新UI。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class SimpleClientActivity extends Activity {

	
	private static final String TAG = "SimpleClientActivity";
	private TextView show;
	private Handler handler = null;
	private String line;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_simple_client);
		show = (TextView)findViewById(R.id.show);
		handler = new Handler();
		new Thread(commRunnable).start();
	}
	
	Runnable commRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				Socket socket = new Socket("192.168.1.188", 30000);
				Log.i(TAG, socket.toString());
				BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				line = br.readLine();
				handler.post(updateRunnable);
				br.close();
				socket.close();
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	};

	Runnable updateRunnable = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			show.setText("来自服务器的数据:"+ line);
		}
	};
		

}

 

抱歉!评论已关闭.