关于“Only the original thread that created a view hierarchy can touch its views.”异常的处理
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;@Overrideprotected 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() {@Overridepublic 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}};Runnable updateRunnable = new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubshow.setText("来自服务器的数据:"+ line);}};}
更多相关文章
- 【Android 界面效果12】EditText中的多行输入问题
- Android EditText 共用TextWatcher,在TextWatcher中确定对应的被
- Android 时间对象操作工具类
- Android进程和线程
- Android 简单的账号密码登陆界面(IO流)
- 主界面监听返回键,退出程序
- 写信息的界面
- android用ViewPager实现欢迎界面