开始的时候,我以为可以直接在主线程里面进行网络的访问,后来发现,在Android4.0之后就不支持这种方法了。所以就要创建一个新的线程去解决这个问题。但是子线程中,又存在着不能够更改UI的限制。那么这个怎么办呢?
通过查询博客,可以采取以下的方式:handler去处理消息并且更改UI,线程进行访问网络,将获得的数据传送给handler进行处理,handler接收到消息之后,用sendMessage函数将message传送给handleMessage进行接下来的更改ui的操作。代码如下:其中digest为自定义的editText控件。
Handler handler = new Handler() { //全局共享
public void handleMessage(android.os.Message msg) {
// 处理消息时需要知道是成功的消息还是失败的消息
switch (msg.what) {
case 1:
digest.setText((String) msg.obj);
break;
case 0:
digest.setText("Failed");
break;
default:
break;
}
}
};
public class MyThread extends Thread {//全局公共线程类
//继承Thread类,并改写其run方法
private final static String TAG = "My Thread ===> ";
public String answer = "";
public void run(){
Log.d(TAG, "run");
try {
System.out.println("已经请求");
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new MyThread().start();
}
});
URL url = new URL("http://xxx.xxx.xxx.xxx:8080"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); connection.addRequestProperty("Connection", "Keep-Alive"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); System.out.println("hell"); InputStream is = connection.getInputStream(); if (200 == connection.getResponseCode()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while (-1 != (len = is.read(buffer))) { baos.write(buffer, 0, len); baos.flush(); } System.out.println("这是网络传回的数据"); System.out.println(baos.toString()); Message msg = handler.obtainMessage(); msg.obj = baos.toString(); msg.what = 1; handler.sendMessage(msg); } else { digest.setText("failed"); } } catch (MalformedURLException e) { Log.i("catch 1", "info is" + e.toString()); e.printStackTrace(); } catch (ProtocolException e) { Log.i("catch 1", "info is" + e.toString()); e.printStackTrace(); } catch (IOException e) { Log.i("catch 1", "info is" + e.toString()); e.printStackTrace(); } for(int i = 0; i<100; i++) { Log.e(TAG, Thread.currentThread().getName() + "i = " + i); } Log.w("hello","开始请求"); } }
add.setOnClickListener(new View.OnClickListener() { //add为button控件
@Override
public void onClick(View view) {
new MyThread().start();
}
});