Http异步下载图片

作者:追风剑情 发布于:2015-8-4 21:50 分类:Android

在AndroidManifest.xml中添加权限配置

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

视图

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

</LinearLayout>

活动

package com.example.androidtest;

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

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

public class NetworkingActivity extends Activity {

	ImageView img;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_networking);
		
		String url = "http://s01.incnjp.com/forum/201506/23/151249wl69l7kl725qwzpe.jpg";
		new DownloadImageTask().execute(url);
	}
	
	private InputStream OpenHttpConnection(String urlString) throws IOException
	{
		InputStream in = null;
		int response = -1;
		
		URL url = new URL(urlString);
		URLConnection conn = url.openConnection();
		
		if(!(conn instanceof HttpURLConnection))
			throw new IOException("Not an HTTP connection");
		
		try {
			HttpURLConnection httpConn = (HttpURLConnection) conn;
			httpConn.setAllowUserInteraction(false);
			httpConn.setInstanceFollowRedirects(true);
			httpConn.setRequestMethod("GET");
			httpConn.connect();
			response = httpConn.getResponseCode();
			if(response == HttpURLConnection.HTTP_OK){
				in = httpConn.getInputStream();
			}
		} catch (Exception ex) {
			Log.d("AndroidTest", ex.getLocalizedMessage());
			throw new IOException("Error connecting");
		}
		
		return in;
	}
	
	private Bitmap DownloadImage(String url){
		Bitmap bitmap = null;
		InputStream in = null;
		try {
			in = OpenHttpConnection(url);
			bitmap = BitmapFactory.decodeStream(in);
			in.close();
		} catch (IOException ex){
			Log.d("AndroidTest", ex.getLocalizedMessage());
		}
		return bitmap;
	}
	
	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
	{
		protected Bitmap doInBackground(String... urls){
			return DownloadImage(urls[0]);
		}
		
		protected void onPostExecute(Bitmap result){
			ImageView img = (ImageView) findViewById(R.id.img);
			img.setImageBitmap(result);
		}
	}
}

运行效果

111111111.png


标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号