[Android] android.view.ViewRoot$CalledFromWrongThreadException

[Android] android.view.ViewRoot$CalledFromWrongThreadException

今日寫軟體中的某個畫面,我使用了new thread來加速圖片的處理以及使用Progressbar,原本以為應該很快就可以寫好的程式,在測試時卻一直跳出exception:android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

問了孤狗大神才知道原來不能在major thread以外的thread更新使用者介面,所以需先在thread中,download圖片至手機中,download完畢時,sendMessage to Handler,接著在把剛剛download下來的圖片設定至bitmap中,並更新使用者介面才能完成整個流程。

public class LocationDetail extends Activity implements Runnable{
    private String imageUrl;
    private ImageView content;
    private ProgressBar myProgressBar;
    int myProgress = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location_detail);

        myProgressBar = (ProgressBar) findViewById(R.id.progressbar);
        myProgressBar.setProgress(myProgress);
        content = (ImageView) findViewById(R.id.content);

        //開啟另一個Thread來download圖片至手機暫存資料夾中
        new Thread(this).start();
    }

    @Override
    public void run() {
        String imageUrl = "abc.jpg";

        URL picUrl = new URL("http://xxx.yyy.zzz/"+ imageUrl);
        URLConnection imageConn = picUrl.openConnection();
        imageConn.connect();

        InputStream imageOnCloud = imageConn.getInputStream();
        String outFileName = "手機存放圖片的路徑" + imageUrl;
     
        OutputStream imageInPhone = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;

        while ((length = imageOnCloud.read(buffer)) > 0) {
            imageInPhone.write(buffer, 0, length);
        }

        imageInPhone.flush();
        imageInPhone.close();
        imageOnCloud.close();

        //圖片下載完畢,sendMessage to Handler做接下來更新UI的動作
        handler.sendEmptyMessage(0);
    }
 
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bitmap bitmap = BitmapFactory.decodeFile("手機存放圖片的路徑" + imageUrl);
            content.setImageBitmap(bitmap);
            myProgressBar.setVisibility(View.GONE);
        }
    }
}
(Visited 20 time, 1 visit today)
Facebooktwittergoogle_plusredditpinterestlinkedinmail
Comments are closed.