Android訊息機制入門

來源:互聯網
上載者:User

標籤:

接著處理《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();        }    }}

 

Android訊息機制入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.