原因: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 界面效果12】EditText中的多行输入问题
  2. Android EditText 共用TextWatcher,在TextWatcher中确定对应的被
  3. Android 时间对象操作工具类
  4. Android进程和线程
  5. Android 简单的账号密码登陆界面(IO流)
  6. 主界面监听返回键,退出程序
  7. 写信息的界面
  8. android用ViewPager实现欢迎界面

随机推荐

  1. 如何保证Android设备的安全性
  2. Android(安卓)Studio(4)---开发人员工作
  3. android 流量统计实现思路
  4. android framework 启动流程
  5. Android(安卓)Studio检测不到新版本问题
  6. Android(安卓)webview
  7. android动态加载(二)
  8. Android颜色透明度设置
  9. android评分条RatingBar自定义设置
  10. RelativeLayout属性和使用, 实现上面view