|
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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.