原因: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;@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);}};}


更多相关文章

  1. Android之Handler用法总结
  2. android 使用Intent传递数据之剪切板
  3. Android内存管理、监测剖析
  4. android中Message机制的灵活应用
  5. android 使用Intent传递数据之剪切板
  6. 2011.06.21(2)——— android invalidate和postInvalidate
  7. android handler消息机制
  8. Android内存泄漏监测(MAT)及解决办法
  9. Android(安卓)UI线程和非UI线程

随机推荐

  1. 多款Android播放器源码集锦
  2. android布局小总结
  3. android 布局xml常用属性
  4. Android之布局属性归纳
  5. Android精简代号
  6. Android应用开发——系统自带样式Android
  7. Android实现TextView跑马灯效果
  8. Android之布局属性归纳
  9. Android(安卓)相对布局
  10. Android之布局属性归纳