码迷,mamicode.com
首页 > 其他好文 > 详细

only the original thread that created a view

时间:2015-07-17 16:16:31      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:handler的小用   主线程更新ui   

本来准备写一个简单的通过url获取网络图片setimage到imageview上去

没想到还是有一些小bug

先把源码供上

package com.example.seturlbitmapdemo;

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {

    protected static final int COMPLETED = 0;
    Bitmap bitmap;
    String url = "http://192.168.1.164/Upload_Files/262/339/201507/5582e259-9e70-478c-91b9-1f787fa11c77.jpg";
    private ImageView iv;
    private Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            if (msg.what == COMPLETED) {  
                iv.setImageBitmap(bitmap);
            }  
        }  
    }; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv = (ImageView) findViewById(R.id.imageView1);

        getPic(iv,url);

    }

    private void getPic(final ImageView iv,final String url) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(url)
                            .openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);                    
                    is.close();

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Message msg = new Message();  
                msg.what = COMPLETED;  
                handler.sendMessage(msg);  
            }
        }).start();
    }

}

xml布局就是一个imageview

我一只告诉自己要用主线程更新ui
我在子线程里面获取数据,用一个handler接受获取数据成功的回调信息msg,然后更新ui,把bitmap设为全局的变量,这样就对了。

版权声明:本文为博主原创文章,未经博主允许不得转载。

only the original thread that created a view

标签:handler的小用   主线程更新ui   

原文地址:http://blog.csdn.net/a4384142/article/details/46927375

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!