|
public void click(View v){ new Thread(){ public void run() { try { String path=et_path.getText().toString().trim(); URL url=new URL(path); HttpURLConnection conection=(HttpURLConnection) url.openConnection(); conection.setRequestMethod("GET");//默认就是gei请求 conection.setConnectTimeout(5000); int code=conection.getResponseCode(); if(code==200){ InputStream in=conection.getInputStream(); String content=StreamTools.readStream(in);
//使用助手告诉系统我要更新UI Message msg=new Message(); msg.obj=content; handler.sendMessage(msg); //随后Handelmessage方法就会执行 }
} catch (Exception e) { e.printStackTrace(); } }; }.start();
}
private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) {
String m=(String) msg.obj; tv_result.setText(m); } };
public class StreamTools { public static String readStream(InputStream in) throws IOException{ int len=-1; //内存输出流 ByteArrayOutputStream baos=new ByteArrayOutputStream(); byte[] buffer=new byte[10240]; while((len=in.read(buffer))!=-1){ baos.write(buffer,0,len); } in.close(); String content=new String(baos.toByteArray()); return content; } } | ||||
|
| ||||
| 1.主线程定义一个Handler 2.使用Handler重写HandleMessage()方法 3.在子线程中使用穿送相应的数据handler.sendMessage(msg) msg来携带信息 | ||||
|
| ||||
| runOnUIThread(action)在UI线程,则立即执行 若不是在UI线程,就发到消息队列中 不管你写在什么位置上调用,action都运行在UI线程中 action是一个Runable run方法中写修改UI的语句 携带数据时用handler | ||||
注意 两种方式都需要在活动销毁时主动调用cancel()销毁
|
| ||||
| setImageUrl();内部封装了一个获取数据,封装成bitmap在展示图片的功能 |
Android基础知识点梳理(4)
最新推荐文章于 2022-09-07 22:25:39 发布