Android开发实现加载网络图片并下载至本地SdCard的方法-创新互联

本文实例讲述了Android开发实现加载网络图片并下载至本地SdCard的方法。分享给大家供大家参考,具体如下:

创新互联建站于2013年开始,先为桥东等服务建站,桥东等地企业,进行企业商务咨询服务。为桥东企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
package com.example.myimagedemo;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
public class MainActivity extends Activity {
  private ImageView mImageView;
  private String imgPath="/file/tupian/20230213/124530.gif";
  private File cache;//缓存路径
  Handler handler=new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
      //显示
      Bitmap b=(Bitmap)msg.obj;
      mImageView.setImageBitmap(b);
      //保存至本地
      File imgFile=new File(cache,"woca.jpg");
      try {
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(imgFile));
        b.compress(Bitmap.CompressFormat.JPEG,80,bos);
        bos.flush();
        bos.close();
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return false;
    }
  });
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mImageView=(ImageView)findViewById(R.id.mImageView);
    //创建缓存路径
    //Environment.getExternalStorageDirectory()获取手机内存卡根路径
    cache=new File(Environment.getExternalStorageDirectory(),"Test");
    if(!cache.exists()){
      cache.mkdirs();
    }
    //耗时操作都要放在子线程操作
    //开启子线程获取输入流
    new Thread(new Runnable() {
      @Override
      public void run() {
        HttpURLConnection conn=null;
        InputStream is=null;
        try {
          URL url=new URL(imgPath);
          //开启连接
          conn=(HttpURLConnection) url.openConnection();
          //设置连接超时
          conn.setConnectTimeout(5000);
          //设置请求方式
          conn.setRequestMethod("GET");
          //conn.connect();
          if(conn.getResponseCode()==200){
            is=conn.getInputStream();
            Bitmap b=BitmapFactory.decodeStream(is);
            //把输入流转化成bitmap格式,以msg形式发送至主线程
            Message msg=new Message();
            msg.obj=b;
            handler.sendMessage(msg);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }finally{
          try {
          //用完记得关闭
            is.close();
            conn.disconnect();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }).start();
  }
}


网页名称:Android开发实现加载网络图片并下载至本地SdCard的方法-创新互联
本文链接:http://ybzwz.com/article/hjeoo.html