浅入浅出Android(015):使用ImageView显示网络图片
博客专区 > 樂天 的博客 > 博客详情
浅入浅出Android(015):使用ImageView显示网络图片
樂天 发表于3年前
浅入浅出Android(015):使用ImageView显示网络图片
  • 发表于 3年前
  • 阅读 42
  • 收藏 1
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

Android studio 版本是0.8.6,android 虚拟机版本是4.*。

1、创建项目MyApplication


2、添加访问网络的权限

在AndroidManifest.xml中添加<uses-permission android:name="android.permission.INTERNET" />,该文件最终内容是:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.letian.myapplication" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3、修改布局文件activity_my.xml

<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity">

    <Button
        android:id="@+id/button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取图片" />

    <ImageView
        android:id="@+id/imageview01"
        android:layout_below="@id/button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>


4、修改MyActivity.java

package com.example.letian.myapplication;

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.Button;
import android.widget.ImageView;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.InputStream;


public class MyActivity extends Activity {

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

        final Button btn01 = (Button) this.findViewById(R.id.button01);
        final ImageView iv01 = (ImageView) this.findViewById(R.id.imageview01);

        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bitmap bitmap=(Bitmap)msg.obj;
                iv01.setImageBitmap(bitmap);
            }
        };

        final Runnable runnable = new Runnable(){
            @Override
            public void run() {
                HttpGet getRequest = new HttpGet("http://static.oschina.net/uploads/user/470/940565_100.jpg?t=1400854721000");
                getRequest.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0");
                try {
                    HttpResponse response = new DefaultHttpClient().execute(getRequest);
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                        InputStream imageStream = response.getEntity().getContent();
                        Bitmap result = BitmapFactory.decodeStream(imageStream);
                        Message msg = new Message();
                        msg.obj=result;
                        handler.sendMessage(msg);
                    } else {
                        throw new Exception("读取失败");
                    }
                } catch (Exception e) {
                    try {
                        throw new Exception("读取失败:\n"+e.toString());
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }

            }
        };

        btn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(runnable).start();
            }
        });
    }


}
上面的runnable中HTTP请求使用了已经封装好的HttpGet,也可以使用HttpURLConnection,如下:

final Runnable runnable = new Runnable(){
    @Override
    public void run() {

        try {
            URL imageUrl = new URL("http://static.oschina.net/uploads/user/470/940565_100.jpg?t=1400854721000");
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 ...");
            conn.connect();
            InputStream is = conn.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            Message msg = new Message();
            msg.obj = bitmap;
            handler.sendMessage(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
};



5、效果



获取图片:



参考:


http://stackoverflow.com/questions/13012702/android-sdk-obtain-image-from-http-get

http://blog.csdn.net/nasebanaru/article/details/17201783
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 132
博文 668
码字总数 147051
作品 3
×
樂天
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: