Android 通过开源框架实现加载网络图片并下载到SD卡通知系统相册显示,(并实现分享图片功能)

本文介绍如何在Android应用中使用开源框架ImageLoader来加载网络图片,并展示图片加载配置。此外,还实现了图片的下载功能,当图片下载到SD卡后,会通知系统相册更新,并提供了一个自定义的分享工具类,支持将图片分享到微信、朋友圈、QQ等社交平台。
摘要由CSDN通过智能技术生成
首先看下本 demo实现的功能

1:实现网络图片的加载显示
2:点击图片底部弹出popupwindow
3:点击分享 实现单个图片分享到:微信,朋友圈,QQ,QQ控件(调用系统)
4:点击下载 实现图片的下载 ,并通知系统相册进行更新

调用开源框架:ImageLoader  (实现图片的加载) 使用githup共享的开源代码实现系统分享的改写
githup 上的连接记不太清了 等下会放出源码  就一个工具类的代码。有兴趣的可以去研究研究

项目里注释写的挺详细的 ,不说废话了直接上代码 :


imageloader配置  
package com.example.downloaddemo;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.graphics.Bitmap.CompressFormat;
import android.os.Vibrator;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;

/**
 * Application
 */
public class LocationApplication extends Application {
	public static ImageLoader imageLoader;

	@Override
	public void onCreate() {
		super.onCreate();
		File cacheDir = StorageUtils.getOwnCacheDirectory(
				getApplicationContext(), "imageloader/hire/Cache");
		imageLoader = ImageLoader.getInstance();
		ImageLoaderConfiguration config3 = new ImageLoaderConfiguration.Builder(
				getApplicationContext())
				.memoryCacheExtraOptions(480, 800)
				// max width, max height即每个缓存文件最大长 .discCacheExtraOptions(480,
				// 800, CompressFormat.JPEG, 75, null) // Can slow ImageLoader,
				// use it carefully (Better don't use it)/设置缓存详细信息不要设置
				.threadPoolSize(3)
				// 线程池内加载的数 .threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
				// You can pass your own memory cache
				// implementation//你可通过自己的内存缓存实 .memoryCacheSize(2 * 1024 *
				// 1024)
				.discCacheSize(50 * 1024 * 1024)
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				// 将保存的url名称用MD5加密
				.tasksProcessingOrder(QueueProcessingType.FIFO)
				.discCacheFileCount(100) // 缓存文件数量
				.discCache(new UnlimitedDiscCache(cacheDir))// 文件储存路径
				.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
				.imageDownloader(
						new BaseImageDownloader(getApplicationContext(),
								5 * 1000, 30 * 1000)) // connectTimeout (5 s),
														// readTimeout (30
														// s)超时时间
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		imageLoader.init(config3);
	}
}

封装好的分享工具类:

package com.example.downloaddemo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Patterns;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidShare extends Dialog implements
		AdapterView.OnItemClickListener {
	private LinearLayout mLayout;
	private GridView mGridView;
	private float mDensity;
	private String msgText = "分享了";
	private String mImgPath;
	private int mScreenOrientation;
	private List<ShareItem> mListData;
	private Handler mHandler = new Handler();

	private Runnable work = new Runnable() {
		public void run() {
			int orient = getScreenOrientation();
			if (orient != mScreenOrientation) {
				if (orient == 0)
					mGridView.setNumColumns(4);
				else {
					mGridView.setNumColumns(6);
				}
				mScreenOrientation = orient;
				((AndroidShare.MyAdapter) mGridView.getAdapter())
						.notifyDataSetChanged();
			}
			mHandler.postDelayed(this, 1000L);
		}
	};

	public AndroidShare(Context context) {
		super(context, R.style.shareDialogTheme);
	}

	public AndroidShare(Context context, int theme, String msgText,
			final String imgUri) {
		super(context, theme);
		this.msgText = msgText;

		if (Patterns.WEB_URL.matcher(imgUri).matches())
			new Thread(new Runnable() {
				public void run() {
					try {
						mImgPath = getImagePath(imgUri, getFileCache());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).start();
		else
			this.mImgPath = imgUri;
	}

	public AndroidShare(Context context, String msgText, final String imgUri) {
		super(context, R.style.shareDialogTheme);
		this.msgText = msgText;

		if (Patterns.WEB_URL.matcher(imgUri).matches())
			new Thread(new Runnable() {
				public void run() {
					try {
						mImgPath = getImagePath(imgUri, getFileCache());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).start();
		else
			this.mImgPath = imgUri;
	}

	void init(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getResources().getDisplayMetrics();
		this.mDensity = dm.density;
		this.mListData = new ArrayList<ShareItem>();
		this.mListData.add(new ShareItem("微信", R.drawable.logo_wechat,
				"com.tencent.mm.ui.tools.ShareImgUI", "com.tencent.mm"));
		this.mListData.add(new ShareItem("朋友圈", R.drawable.logo_wechatmoments,
				"com.tencent.mm.ui.tools.ShareToTimeLineUI", "com.tencent.mm"));
		this.mListData.add(new ShareItem("qq", R.drawable.logo_qq,
				"com.tencent.mobileqq.activity.JumpActivity",
				"com.tencent.mobileqq"));
		this.mListData
				.add(new ShareItem("qq空间", R.drawable.logo_qzone,
						"com.qzone.ui.operation.QZonePublishMoodActivity",
						"com.qzone"));

		this.mLayout = new LinearLayout(context);
		this.mLayout.setOrientation(1);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2);
		params.leftMargin = ((int) (10.0F * this.mDensity));
		params.rightMargin = ((int) (10.0F * this.mDensity));
		this.mLayout.setLayoutParams(params);
		this.mLayout.setBackgroundColor(Color.parseColor("#D9DEDF"));

		this.mGridView = new GridView(context);
		this.mGridView.setLayoutParams(new ViewGroup.LayoutParams(-1, -2));
		this.mGridView.setGravity(17);
		this.mGridView.setHorizontalSpacing((int) (10.0F * this.mDensity));
		this.mGridView.setVerticalSpacing((int) (10.0F * this.mDensity));
		this.mGridView.setStretchMode(1);
		this.mGridView.setColumnWidth((int) (90.0F * this.mDensity));
		this.mGridView.setHorizontalScrollBarEnabled(false);
		this.mGridView.setVerticalScrollBarEnabled(false);
		this.mLayout.addView(this.mGridView);
	}

	public List<ComponentName> queryPackage() {
		List<ComponentName> cns = new ArrayList<ComponentName>();
		Intent i = new Intent("android.intent.action.SEND");
		i.setType("image/*");
		List<ResolveInfo> resolveInfo = getContext().getPackageManager()
				.queryIntentActivities(i, 0);
		for (ResolveInfo info : resolveInfo) {
			ActivityInfo ac = info.activityInfo;
			ComponentName cn = new ComponentName(ac.packageName, ac.name);
			cns.add(cn);
		}
		return cns;
	}

	public boolean isAvilible(Context context, String packageName) {
		PackageManager packageManager = context.getPackageManager();

		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
		for (int i = 0; i < pinfo.size(); i++) {
			if (((PackageInfo) pinfo.get(i)).packageName
					.equalsIgnoreCase(packageName))
				return true;
		}
		return false;
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Context context = getContext();
		init(context);
		setContentView(this.mLayout);

		getWindow().setGravity(80);

		if (getScreenOrientation() == 0) {
			this.mScreenOrientation = 0;
			this.mGridView.setNumColumns(4);
		} else {
			this.mGridView.setNumColumns(6);
			this.mScreenOrientation = 1;
		}
		this.mGridView.setAdapter(new MyAdapter());
		this.mGridView.setOnItemClickListener(this);

		this.mHandler.postDelayed(this.work, 1000L);

		setOnDismissListener(new DialogInterface.OnDismissListener() {
			public void onDismiss(DialogInterface dialog) {
				mHandler.removeCallbacks(work);
			}
		});
	}

	public void show() {
		super.show();
	}

	@SuppressLint("NewApi")
	public int getScreenOrientation() {
		int landscape = 0;
		int portrait = 1;
		Point pt = new Point();
		getWindow().getWindowManager().getDefaultDisplay().getSize(pt);
		int width = pt.x;
		int height = pt.y;
		return width > height ? portrait : landscape;
	}

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ShareItem share = (ShareItem) this.mListData.get(position);
		shareMsg(getContext(), "分享到...", this.msgText, this.mImgPath, share);
	}

	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	private void shareMsg(Context context, String msgTitle, String msgText,
			String imgPath, ShareItem share) {
		if (!share.packageName.isEmpty()
				&& !isAvilible(getContext(), share.packageName)) {
			Toast.makeText(getContext(), "请先安装" + share.title,
					Toast.LENGTH_SHORT).show();
			return;
		}

		Intent intent = new Intent("android.intent.action.SEND");
		if ((imgPath == null) || (imgPath.equals(""))) {
			intent.setType("text/plain");
		} else {
			File f = new File(imgPath);
			if ((f != null) && (f.exists()) && (f.isFile())) {
				intent.setType("image/png");
				intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
			}
		}

		intent.putExtra(Intent.EXTRA_SUBJECT, msgTitle);
		intent.putExtra(Intent.EXTRA_TEXT, msgText);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (!share.packageName.isEmpty()) {
			intent.setComponent(new ComponentName(share.packageName,
					share.activityName));
			context.startActivity(intent);
		} else {
			context.startActivity(Intent.createChooser(intent, msgTitle));
		}
	}

	private File getFileCache() {
		File cache = null;

		if (Environment.getExternalStorageState().equals("mounted"))
			cache = new File(Environment.getExternalStorageDirectory() + "/."
					+ getContext().getPackageName());
		else {
			cache = new File(getContext().getCacheDir().getAbsolutePath()
					+ "/." + getContext().getPackageName());
		}
		if ((cache != null) && (!cache.exists())) {
			cache.mkdirs();
		}
		return cache;
	}

	public String getImagePath(String imageUrl, File cache) throws Exception {
		String name = imageUrl.hashCode()
				+ imageUrl.substring(imageUrl.lastIndexOf("."));
		File file = new File(cache, name);

		if (file.exists()) {
			return file.getAbsolutePath();
		}

		URL url = new URL(imageUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		conn.setDoInput(true);
		if (conn.getResponseCode() == 200) {
			InputStream is = conn.getInputStream();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
			is.close();
			fos.close();

			return file.getAbsolutePath();
		}

		return null;
	}

	private final class MyAdapter extends BaseAdapter {
		private static final int image_id = 256;
		private static final int tv_id = 512;

		public MyAdapter() {
		}

		public int getCount() {
			return mListData.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0L;
		}

		private View getItemView() {
			LinearLayout item = new LinearLayout(getContext());
			item.setOrientation(1);
			int padding = (int) (10.0F * mDensity);
			item.setPadding(padding, padding, padding, padding);
			item.setGravity(17);
			ImageView iv = new ImageView(getContext());
			item.addView(iv);
			iv.setLayoutParams(new LinearLayout.LayoutParams(-2, -2));
			iv.setId(image_id);
			TextView tv = new TextView(getContext());
			item.addView(tv);
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					-2, -2);
			layoutParams.topMargin = ((int) (5.0F * mDensity));
			tv.setLayoutParams(layoutParams);
			tv.setTextColor(Color.parseColor("#212121"));
			tv.setTextSize(16.0F);
			tv.setId(tv_id);
			return item;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = getItemView();
			}
			ImageView iv = (ImageView) convertView.findViewById(image_id);
			TextView tv = (TextView) convertView.findViewById(tv_id);
			AndroidShare.ShareItem item = (AndroidShare.ShareItem) mListData
					.get(position);
			iv.setImageResource(item.logo);
			tv.setText(item.title);
			return convertView;
		}
	}

	private class ShareItem {
		String title;
		int logo;
		String activityName;
		String packageName;

		public ShareItem(String title, int logo, String activityName,
				String packageName) {
			this.title = title;
			this.logo = logo;
			this.activityName = activityName;
			this.packageName = packageName;
		}
	}
}
主要功能代码:

package com.example.downloaddemo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	// 图片url
	private String phat = "http://www.qqya.com/userimg/15/13100P04140.jpg";
	// 设置SD路径
	private final static String ALBUM_PATH = Environment
			.getExternalStorageDirectory() + "/baocunlujing/";
	private File dirFile, myCaptureFile;
	private ProgressDialog mSaveDialog = null;
	private Bitmap mBitmaps;
	private String mFileName;
	private ImageView img;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		inti();
	}

	/**
	 * 初始化ui
	 */
	void inti() {
		img = (ImageView) findViewById(R.id.img);
		img.setOnClickListener(this);
		/*
		 * 调用开源框架 ImageLoader加载并显示图片
		 */
		ImageLoader.getInstance().loadImage(phat,
				new SimpleImageLoadingListener() {
					private Bitmap mBitmap;
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap mBitmap) {
						this.mBitmap = mBitmap;
						// 将bitmap转换为全局变量,以供下方调用
						mBitmaps = mBitmap;
						super.onLoadingComplete(imageUri, view, mBitmap);
						img.setImageBitmap(mBitmap);
					}
				});
			}

	/**
	 * 保存文件
	 * 
	 * @param bm
	 * @param fileName
	 * @throws IOException
	 */
	public void saveFile(Bitmap bm, String fileName) throws IOException {
		dirFile = new File(ALBUM_PATH);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		myCaptureFile = new File(ALBUM_PATH + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
	}

	/**
	 * 弹出窗
	 */
	private void showDialog() {
		View view = LayoutInflater.from(this).inflate(R.layout.image_pager,
				null);
		final Dialog dialog = new Dialog(this,
				R.style.transparentFrameWindowStyle);
		dialog.setContentView(view, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		Window window = dialog.getWindow();
		// 设置显示动画
		window.setWindowAnimations(R.style.main_menu_animstyle);
		WindowManager.LayoutParams wl = window.getAttributes();
		wl.x = 0;
		wl.y = this.getWindowManager().getDefaultDisplay().getHeight();
		// 以下这两句是为了保证按钮可以水平满屏
		wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
		wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
		// 设置显示位置
		dialog.onWindowAttributesChanged(wl);
		// 设置点击外围解散
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
		Button sendBtn = (Button) view.findViewById(R.id.quxiao);
		Button sendBtn1 = (Button) view.findViewById(R.id.xiazai);
		Button share = (Button) view.findViewById(R.id.share);
		// 下载
		sendBtn1.setOnClickListener(new View.OnClickListener() {
			@SuppressLint("NewApi")
			@Override
			public void onClick(View arg0) {
				// 图片名字 自定义
				String name = "tupianname.jpg";
				// 替换名字
				mFileName = name;
				mSaveDialog = ProgressDialog.show(MainActivity.this, "保存图片",
						"图片正在保存中,请稍等...", true);

				try {
					// 无异常保存成功 产生异常保存失败
					saveFile(mBitmaps, mFileName);
					mSaveDialog.dismiss();
					// 保存成功 通知相册进行显示最新照片
					Toast.makeText(MainActivity.this, "图片保存到:我的文件" + mFileName,
							Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(
							Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
					Uri uri = Uri.fromFile(myCaptureFile);
					intent.setData(uri);
					sendBroadcast(intent);
				} catch (IOException e) {
					Toast.makeText(MainActivity.this, "图片保存失败!",
							Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
			}

		});
		// 分享
		share.setOnClickListener(new View.OnClickListener() {
			@SuppressLint("NewApi")
			@Override
			public void onClick(View arg0) {
				// 调用 系统分享功能
				AndroidShare as = new AndroidShare(MainActivity.this, "分享着张图片",
						phat);
				as.show();
			}
		});
		// 取消框
		sendBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
	}

	/*
	 * img的点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img:
			// 当图片未加载的情况下 弹出提示
			if (mBitmaps != null) {
				showDialog();
			} else {
				Toast.makeText(getApplicationContext(), "图片未加载成功", 0).show();
			}
			break;
		default:
			break;
		}
	}
}

布局比较简单就不放出来了 。


下面放下成果,



DOME  下载 :http://download.csdn.net/detail/a153013144/9266545




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值