android(19)(两种方式从网络抓取图片显示在本地)

本文介绍两种不同的图片加载方法:一种是手动实现的网络图片加载方案,包括从网络获取图片并显示到ImageView中;另一种则是利用第三方开源框架android-smart-image-view进行图片加载,简化了开发流程。
第一种方式(自己写的):
1.布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/et_url"
            android:layout_width="0dip"
            android:text="http://imgstatic.baidu.com/img/image/d833c895d143ad4bf450b6dd80025aafa40f06b4_%E5%89%AF%E6%9C%AC.jpg"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:layout_weight="1" />

        <Button
            android:id="@+id/btn_submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Go"
            android:textSize="20sp" />
    </LinearLayout>

</LinearLayout>
2.业务逻辑的实现代码:
public class MainActivity extends Activity implements OnClickListener {

    private static final String TAG = "MainActivity";
    protected static final int ERROR = 1;
    private EditText etUrl;
    private ImageView ivIcon;
    private final int SUCCESS = 0;

    private Handler handler = new Handler() {

        /**
         * 接收消息
         */
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Log.i(TAG, "what = " + msg.what);
            if(msg.what == SUCCESS) {   // 当前是访问网络, 去显示图片
                ivIcon.setImageBitmap((Bitmap) msg.obj);        // 设置imageView显示的图片
            } 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);

        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        etUrl = (EditText) findViewById(R.id.et_url);

        findViewById(R.id.btn_submit).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        final String url = etUrl.getText().toString();//获取editext中的url
        //访问网络需要开启一个子线程(耗时的操作都得放在子线程里面)
        new Thread(new Runnable() {

            @Override
            public void run() {
                Bitmap bitmap = getImageFromNet(url);

//              ivIcon.setImageBitmap(bitmap);      // 设置imageView显示的图片
                if(bitmap != null) {
                    Message msg = new Message();
                    msg.what = SUCCESS;
                    msg.obj = bitmap;
                    handler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.what = ERROR;
                    handler.sendMessage(msg);
                }
            }}).start();

    }

    /**
     * 根据url连接取网络抓去图片返回
     * @param url
     * @return url对应的图片
     */
    private Bitmap getImageFromNet(String url) {
        HttpURLConnection conn = null;
        try {
            URL mURL = new URL(url);    // 创建一个url对象

            // 得到http的连接对象
            conn = (HttpURLConnection) mURL.openConnection();

            conn.setRequestMethod("GET");       // 设置请求方法为Get
            conn.setConnectTimeout(10000);      // 设置连接服务器的超时时间, 如果超过10秒钟, 没有连接成功, 会抛异常
            conn.setReadTimeout(5000);      // 设置读取数据时超时时间, 如果超过5秒, 抛异常

            conn.connect();     // 开始链接

            int responseCode = conn.getResponseCode(); // 得到服务器的响应码
            if(responseCode == 200) {
                // 访问成功
                InputStream is = conn.getInputStream(); // 获得服务器返回的流数据

                Bitmap bitmap = BitmapFactory.decodeStream(is); // 根据 流数据 创建一个bitmap位图对象,decode:解码

                return bitmap;
            } else {
                Log.i(TAG, "访问失败: responseCode = " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn != null) {//如果conn还一直连着就断开连接
                conn.disconnect();      // 断开连接
            }
        }
        return null;
    }
第二种方式(使用开源的第三方框架:android-smart-image-view-master):
1.布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <com.loopj.android.image.SmartImageView
        android:id="@+id/iv_icon"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/et_url"
            android:layout_width="0dip"
            android:text="http://imgstatic.baidu.com/img/image/d833c895d143ad4bf450b6dd80025aafa40f06b4_%E5%89%AF%E6%9C%AC.jpg"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:layout_weight="1" />

        <Button
            android:id="@+id/btn_submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Go"
            android:textSize="20sp" />
    </LinearLayout>

</LinearLayout>
2.业务逻辑的实现代码:
public class MainActivity2 extends Activity implements OnClickListener {

    private EditText etUrl;
    private SmartImageView mImageView;

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

        etUrl = (EditText) findViewById(R.id.et_url);
        mImageView = (SmartImageView) findViewById(R.id.iv_icon);

        findViewById(R.id.btn_submit).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        // 1. 取出url, 抓取图片
        String url = etUrl.getText().toString();

        mImageView.setImageUrl(url);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值