用android原生代码实现联网得到图片

package com.bruce.okhttpdemo;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;

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

public class MainActivity extends Activity {
    ImageView img;

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

    private void initWidget() {
        img = (ImageView) findViewById(R.id.img);
        //
        new AsyncTask() {  //异步删除数据,并且设置到适配器
            @Override
            protected Object doInBackground(Object[] objects) {
                URL url = null;
                try {
                    url = new URL("http://d.hiphotos.baidu.com/news/q%3D100/sign=b96864cc8cd4b31cf63c90bbb7d7276f/d6ca7bcb0a46f21f4d8c21dcf1246b600d33ae81.jpg");
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                return getusericon(url);
            }

            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
                Bitmap bitmap = (Bitmap) o;
                img.setImageBitmap(bitmap);
            }
        }.execute();
    }

    /**
     * 根据一个网络连接(URL)获取bitmap图像
     *
     * @param imageUri
     * @return
     */
    public static Bitmap getusericon(URL imageUri) {
        // 显示网络上的图片
        URL myFileUrl = imageUri;
        Bitmap bitmap = null;
        try {
            HttpURLConnection conn = (HttpURLConnection) myFileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}

你可能感兴趣的:(用android原生代码实现联网得到图片)