Android学习八:获取网络图片

看到QQ群里有个朋友说加载图片内存溢出的问题,所以就按照自己的想法试试的。但是按照他的方法,不知道为何没有发生内存溢出,不知道什么情况。

写这篇文章主要有三个目的:

  1.多线程的学习

  2.图片加载的学习

  3.编程练手

好了,上代码

package org.tonny;

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

import android.R;
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.view.View;
import android.widget.ImageView;

public class NetpictActivity extends Activity
{
    private Bitmap mBitmap = null;
    private ImageView mView = null;
    private Handler mHandler = null;
    
    //网上随便找的一个图片
    private final String mUri = "http://pic5.nipic.com/20100118/3822085_173909557153_2.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        //这边的用R.id.layout方法出现了问题,所以只好用数值代替了
        setContentView(0x7f030000);
        
        mView = (ImageView)this.findViewById(0x7f050000);
        mHandler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                switch (msg.what)
                {
                case 1:
                    if (mView == null || mBitmap == null)
                    {
                        return;
                    }
                    mView.setImageBitmap(mBitmap);
                    break;
                }
            }
        };
    }

    public void onBtnShowClick(View v)
    {
        Thread thrad = new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    URL url = new URL(mUri);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream inputStream = conn.getInputStream();
                    
                    //mBitmap是一个全局变量,用于存储图片的数据
                    mBitmap = BitmapFactory.decodeStream(inputStream);
                    Message msg = mHandler.obtainMessage();
                    //注意这里只传输了类型
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                    inputStream.close();
                }
                catch (MalformedURLException e)
                {
                    e.printStackTrace();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        };
        thrad.start();
    }
}

注意在清单文件里配置访问网络的权限

好了,继续学习

posted @ 2015-04-28 00:21  oneqhw  阅读(194)  评论(0编辑  收藏  举报