Android 實如今線程中聯網
其實咱們要牢記的是,對數據流的操做都是阻塞的,在通常狀況下,咱們是不須要考慮這個問題的,可是在Android 實現聯網的時候,咱們必須考慮到這個問題。好比:從網絡上下載一張圖片:
Java代碼:
- public Bitmap returnBitmap(String url)
- {
- URL myFileUrl = null;
- Bitmap bitmap = null;
- try{
- myFileUrl = new URL(url);
- }catch(MalformedURLException e){
- e.printStackTrace();
- return null;
- };
- try{
- HttpURLConnection conn = (HttpURLConnection)myFileUrl.openConnection();
- conn.setDoInput(true);
- conn.connect();
- InputStream is = conn.getInputStream();
- bitmap = BitmapFactroy.decodeStream(is);
- is.close();
- }catch(IOException e){
- e.printStackTrace();
- }
- return bitmap;
- }
複製代碼
因爲網絡鏈接須要很長的時間,須要3-5秒,甚至更長的時間才能返回頁面的內容。若是此鏈接動做直接在主線程,也就是UI線程中處理,會發生什麼情 況呢? 整個程序處於等待狀態,界面彷佛是「死」掉了。爲了解決這個問題,必須把這個任務放置到單獨線程中運行,避免阻塞UI線程,這樣就不會對主線程有任何影 響。舉個例子以下:
Java代碼:
- private void connect(String strURL){
- new Thread() {
- public void run() {
- try {
- HttpClient client = new DefaultHttpClient();
- // params[0]表明鏈接的url
- HttpGet get = new HttpGet(url.getText().toString());
- HttpResponse response = client.execute(get);
- HttpEntity entity = response.getEntity();
- long length = entity.getContentLength();
- InputStream is = entity.getContent();
- String s = null;
- if (is != null) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buf = new byte[128];
- int ch = -1;
- int count = 0;
- while ((ch = is.read(buf)) != -1) {
- baos.write(buf, 0, ch);
- count += ch;
- }
- s = new String(baos.toByteArray());
- Log.V(「moandroid sample」,s);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
- }
複製代碼
使用Handler更新界面
如何將下載的信息顯示在界面上了,好比說下載的進度。Android SDK平臺只容許在主線程中調用相關View的方法來更新界面。若是返回結果在新線程中得到,那麼必須藉助Handler來更新界面。爲此,在界面 Activity中建立一個Handler對象,並在handleMessage()中更新UI。
Java代碼:
- //Task在另外的線程執行,不能直接在Task中更新UI,所以建立了Handler
- private Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- String m = (String) msg.obj;
- message.setText(m);
- }
- };
-
- //只須要將上面的
- Log.V(「moandroid sample」,s);
-
- //替換爲:
- s = new String(baos.toByteArray());
- Message mg = Message.obtain();
- mg.obj = s;
- handler.sendMessage(mg);
歡迎關注本站公眾號,獲取更多信息