Android利用HTTP协议加载网络图片

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010214991/article/details/48493647

转载请注明出处:http://blog.csdn.net/u010214991/article/details/48493647

给出一张图片的网址,我们怎么把这张图片加载到我们的ImageView控件显示呢?

由于采用网络请求,我们必须在AndroidManifest.xml添加权限<uses-permission android:name="android.permission.INTERNET"/>

由于是网络请求数据,我们必须在开辟一条线程来完成数据请求,得到数据后最终回到主线程刷新UI显示图片即可。

好了,该说的已经说了,下面直接贴代码了。


1、MainActivity.java

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

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;

public class MainActivity extends Activity {

	private ImageView imageView;
	private final String PATH = "https://www.baidu.com/img/bdlogo.png";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView = (ImageView) findViewById(R.id.imageView1);

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpClient httpClient = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(PATH);
				try {
					HttpResponse httpResponse = httpClient.execute(httpGet);
					if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
						byte[] data = EntityUtils.toByteArray(httpResponse
								.getEntity());
						Message message = Message.obtain();
						message.obj = data;
						message.what = RESULT_OK;
						handler.sendMessage(message);
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					if (httpClient != null
							&& httpClient.getConnectionManager() != null) {
						httpClient.getConnectionManager().shutdown();
					}
				}

			}
		}).start();

	}

	public Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg.what == RESULT_OK) {
				byte[] data = (byte[]) msg.obj;
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
						data.length);
				imageView.setImageBitmap(bitmap);
			}

		};
	};

}


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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
   
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

3、AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.de"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <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="com.example.de.MainActivity"
            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>


猜你喜欢

转载自blog.csdn.net/u010214991/article/details/48493647