Android 图片下载并显示

package com.test.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

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

import com.test.R;

public class BitmapActivity extends Activity {

	private ImageView imageView ;
	private final static String IMAGEURL = "https://gss1.bdstatic.com/5eN1dDebRNRTm2_p8IuM_a/res/img/logo/logo201509091.png";
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			File file = (File)msg.obj;
			Bitmap bitmap = null;
			try {
				bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			imageView.setImageBitmap(bitmap);
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.bitmap);
		imageView = (ImageView)findViewById(R.id.imageView);
		new Thread(){
			@Override
			public void run() {
				Message message = handler.obtainMessage();
				message.obj = downloadFile(IMAGEURL);
				message.sendToTarget();
			}
		}.start();
	}
	//下载图片
	private File downloadFile(String urlStr){
		URL url = null ;
		InputStream input = null ;
		OutputStream output = null ;
		File file = null ;
		try {
			url = new URL(urlStr);
			URLConnection  urlConnection = url.openConnection();
			urlConnection.setConnectTimeout(5*1000);  
			input = urlConnection.getInputStream();
			file = File.createTempFile("xxxx", "jpg");
			output = new FileOutputStream(file) ; 
			byte[] byt = new byte[1024];
			int length = 0;
			// 开始读取
	        while ((length = input.read(byt)) != -1) {  
	        	output.write(byt, 0, length);  
	        }  
	        input.close();
			output.close();
			System.out.println("下载完成");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("下载出错");
		}
		return file ;
	}
}

猜你喜欢

转载自forlan.iteye.com/blog/2253000