封装Android加载网络图片

直接贴代码吧


<pre name="code" class="java">/**
 * 工具类,用于获得要加载的图片资源
 * 
 * @author LangK
 * 
 */

public class ImageHelper extends AsyncTask<String, Void, String> {
	private static final String TAG = ImageHelper.class;
	ImageView imageView;
	private Context mContext;
	private String webServerStr;
        //本地路径
	private String localfile = Environment.getExternalStorageDirectory()
			.getPath() + "/packename/image";
	private String imageName;

	public ImageHelper(ImageView imageView, Context mContext) {
		// TODO Auto-generated constructor stub
		this.imageView = imageView;
		this.mContext = mContext;
               //网络图片路径的前缀,没有可以设为空“”
		this.webServerStr = HttpUtil.IMAGESERVER;
	}

	@Override
	protected String doInBackground(String... urls) {
		String result = null;
		imageName = urls[0];
		if (imageName==null||imageName.equals("")) {
			return "";
		}
		HttpURLConnection connection = null;
		InputStream is = null;
		RandomAccessFile randomAccessFile = null;
		if (Util.isSDCardExist()) {
			try {
				File file = new File(localfile);
				if (!file.exists()) {
					file.mkdirs();
				}
				String localfilepath = localfile + "/" + imageName;

				file = new File(localfilepath);
				if (file.exists()) {
					return file.getAbsolutePath();
				}
				
				String encodedURL = URLEncoder.encode(imageName, "UTF-8");
				String urlStr = webServerStr + encodedURL;
				Log.d(TAG, "文件下载地址:" + urlStr.toString());
				URL url = new URL(urlStr);
				connection = (HttpURLConnection) url.openConnection();
				connection.setConnectTimeout(5000);
				connection.setRequestMethod("GET");
				long fileSize = connection.getContentLength();
				int responseCode = connection.getResponseCode();
				Log.d(TAG, "文件下载状态码"+responseCode);
				if (fileSize==0||responseCode!=200) {
					if (connection!=null) {
						connection.disconnect();
					}
					return "";
				}
				
				// 将要下载的文件写到保存在保存路径下的文件中
				randomAccessFile = new RandomAccessFile(localfilepath, "rwd");
				is = connection.getInputStream();
				if (is != null) {
					byte[] buffer = new byte[4096];
					int length = -1;
					while ((length = is.read(buffer)) != -1) {
						randomAccessFile.write(buffer, 0, length);
					}
					Log.d(TAG, "下载" + imageName + "文件成功");
				}
				result = file.getAbsolutePath();
			} catch (Exception e) {
				// result = false;
				Log.d(TAG, imageName + "下载文件出现异常", e);
				e.printStackTrace();
			} finally {
				try {
					if (is != null) {
						is.close();
						is=null;
					}
					if (randomAccessFile!=null) {
						randomAccessFile.close();
						randomAccessFile=null;
					}
					if (connection!=null) {
						connection.disconnect();
					}
				} catch (Exception e) {
					Log.d(TAG, imageName + "关闭文件出现异常", e);
					e.printStackTrace();
				}
			}
		} else {
			Log.d(TAG, "SD卡不存在,请检查SD卡是否插好");
		}

		return result;
	}

	/**
	 * 获取下载好的图片
	 */
	@Override
	protected void onPostExecute(String result) {
		BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
		bitmapOptions.inSampleSize = 2;
//		bitmapOptions.inJustDecodeBounds= true;
		if (result == null||result.equals("")) {
			if (imageView != null) {
				imageView.setBackgroundResource(R.drawable.ztephone);
			}
		} else {
			if (imageView != null) {
//				int windowWidth = mContext.getResources().getDisplayMetrics().widthPixels;
				Bitmap map = null;
				map = BitmapFactory.decodeFile(result,bitmapOptions);
				if (map==null) {
					imageView.setBackgroundResource(R.drawable.ztephone);
				}else {
	//				int imageWidth = map.getWidth();
	//				int imageHeight = map.getHeight();
	//				map = BitmapUtil.zoomImg(map, imageWidth * windowWidth
	//						/ imageWidth, imageHeight * windowWidth / imageWidth);
					imageView.setImageBitmap(map);
				}
			}
		}
	}
}

}}
 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值