Android 图片下载并显示

来源:互联网 发布:笔记本触摸手写软件 编辑:程序博客网 时间:2024/05/29 19:50
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(){@Overridepublic 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);}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.bitmap);imageView = (ImageView)findViewById(R.id.imageView);new Thread(){@Overridepublic 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 ;}}
0 0