安卓线程无法修改控件,如何解决
一、安卓的Handler消息处理机制
- 安卓创建Socket客户端,并把接受到服务端的数据刷新到控件上。
- 代码主线程中创建Handler机制,用于刷新UI控件,并且创建Bundle用于数据传递。客户端线程中创建Bundle存储数据,并通过主线程传递的Handler机制返回数据。
- 主线程
package com.example.jiangyo.learn; import NetUtils.NetUtils; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { Handler handler; TextView tx; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tx = (TextView) findViewById(R.id.tx); handler = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); Bundle b = msg.getData(); String string = b.getString("msg"); tx.setText(string); } }; } public void sendMessage(View v) { switch (v.getId()) { case R.id.fh: NetUtils.sendMessageHandler("gofoward",handler); break; } } }
- 客户端
package NetUtils; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import android.os.Bundle; import android.os.Handler; import android.os.Message; public class NetUtils { public static void sendMessageHandler(final String command, final Handler h) { new Thread(new Runnable() { public void run() { // TODO Auto-generated method stub try { Socket client = new Socket("192.168.101.77", 8888); OutputStream out = client.getOutputStream();// 获得数据发送通道 out.write(command.getBytes());// 发送通道,发送数据 int len; InputStream in = client.getInputStream(); byte[] data = new byte[128]; len = in.read(data); String str = new String(data,0,len); Message msg = new Message(); Bundle b = new Bundle(); b.putString("msg", str); msg.setData(b); h.sendMessage(msg); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } }
- XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#000000" tools:context=".MainActivity" > <Button android:id="@+id/fh" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="sendMessage" android:text="发起网络请求" /> <TextView android:id="@+id/tx" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="35dp" android:layout_centerInParent="true" android:textColor="#ffffff" /> </RelativeLayout>