Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Android消息機制入門,android機制入門

Android消息機制入門,android機制入門

編輯:關於android開發

Android消息機制入門,android機制入門


接著處理《Android 網絡圖片查看器》中出現的問題

使用添加子線程,修改原程序:

package com.wuyudong.imagesviewer;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpConnection;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText et_path;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_path = (EditText) findViewById(R.id.et_path);
        iv = (ImageView) findViewById(R.id.iv);
    }

    public void click(View view) {

        final String path = et_path.getText().toString().trim();
        if (TextUtils.isEmpty(path)) {
            Toast.makeText(this, "圖片路徑不能為空", 0).show();
        } else {
            new Thread() {
                @Override
                public void run() {
                    // 連接服務器get請求獲取圖片
                    try {
                        URL url = new URL(path);

                        // 根據url發送http的請求
                        HttpURLConnection conn = (HttpURLConnection) url
                                .openConnection();
                        // 設置請求的方式
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        conn.setReadTimeout(5000);
                        conn.setRequestProperty(
                                "User-Agent",
                                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
                        int code = conn.getResponseCode();
                        if (code == 200) {
                            InputStream is = conn.getInputStream();
                            Bitmap bitmap = BitmapFactory.decodeStream(is);
                            iv.setImageBitmap(bitmap);
                        } else {
                            Toast.makeText(MainActivity.this, "顯示圖片失敗", 0)
                                    .show();
                        }

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this, "訪問獲取圖片失敗", 0).show();
                    }
                }

            }.start();
        }

    }

}

運行項目後報錯:

06-27 19:27:59.613: W/System.err(2471): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

誰創建了view對象,誰才能動修改view。

代碼:iv.setImageBitmap(bitmap);目的就是為了修改UI

也即是主線程才可以修改。為了控制多線程修改view同步問題而設定的

修改後的代碼如下:

package com.wuyudong.imagesviewer;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpConnection;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    protected static final int CHANGE_UI = 1;
    protected static final int ERROR = 2;
    private EditText et_path;
    private ImageView iv;

    // 1、主線程創建消息處理器
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == CHANGE_UI) {
                Bitmap bitmap = (Bitmap) msg.obj;
                iv.setImageBitmap(bitmap);
            } else if (msg.what == ERROR) {
                Toast.makeText(MainActivity.this, "訪問獲取圖片失敗", 0).show();
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_path = (EditText) findViewById(R.id.et_path);
        iv = (ImageView) findViewById(R.id.iv);
    }

    public void click(View view) {

        final String path = et_path.getText().toString().trim();
        if (TextUtils.isEmpty(path)) {
            Toast.makeText(this, "圖片路徑不能為空", 0).show();
        } else {
            new Thread() {
                @Override
                public void run() {
                    // 連接服務器get請求獲取圖片
                    try {
                        URL url = new URL(path);

                        // 根據url發送http的請求
                        HttpURLConnection conn = (HttpURLConnection) url
                                .openConnection();
                        // 設置請求的方式
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        conn.setReadTimeout(5000);
                        conn.setRequestProperty(
                                "User-Agent",
                                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
                        // 得到服務器返回的響應碼
                        int code = conn.getResponseCode();
                        if (code == 200) {
                            InputStream is = conn.getInputStream();
                            Bitmap bitmap = BitmapFactory.decodeStream(is);
                            // iv.setImageBitmap(bitmap);
                            // TODO:告訴主線程一個消息:幫我更改界面,內容:bitmap
                            Message msg = new Message();
                            msg.what = CHANGE_UI;
                            msg.obj = bitmap;
                            handler.sendMessage(msg);

                        } else {
                            // Toast.makeText(MainActivity.this, "顯示圖片失敗", 0)
                            // .show();
                            Message msg = new Message();
                            msg.what = ERROR;
                            handler.sendMessage(msg);
                        }

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        // Toast.makeText(MainActivity.this, "訪問獲取圖片失敗",
                        // 0).show();
                        Message msg = new Message();
                        msg.what = ERROR;
                        handler.sendMessage(msg);
                    }
                }

            }.start();
        }

    }

}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved