保存图片到本地和分享多张图片到QQ、微信、WhatsApp、Facebook等平台
一、分享图片到各个平台多种方式:如第三方的sdk:ShardSDK,直接通过分享到的平台的包名来分享图片的原生方法
1.通过ShareSDK分享图片,不要忘记导入相应的应用包和初始化ShardSDK哦
/*** 分享*/
private void share() {OnekeyShare oks = new OnekeyShare();// 关闭sso授权oks.disableSSOWhenAuthorize();// title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间等使用oks.setTitle(nameShare);// 商品编号 code, nameShare, imageUrlShare// titleUrl是标题的网络链接,QQ和QQ空间等使用oks.setTitleUrl(MyConfig.shopUrl + code);// text是分享文本,所有平台都需要这个字段oks.setText(nameShare + " " + MyConfig.shopUrl + code);// imagePath是图片的本地路径,Linked-In以外的平台都支持此参数// oks.setImagePath("/sdcard/pic.png");// 确保SDcard下面存在此张图片// 网络路径获取图片oks.setImageUrl(imageUrlShare);// 商品的图片网址//oks.setImageArray();//分享图片集合// oks.setImageUrl("http://www.vipstation.com.hk/images/itemimg/L16454754.jpg");// url仅在微信(包括好友和朋友圈)中使用oks.setUrl(MyConfig.shopUrl + code);// comment是我对这条分享的评论,仅在人人网和QQ空间使用// oks.setComment("我是测试评论文本");// site是分享此内容的网站名称,仅在QQ空间使用// oks.setSite(getString(R.string.app_name));// siteUrl是分享此内容的网站地址,仅在QQ空间使用// oks.setSiteUrl(MyConfig.shopUrl + code);/* 这里添加自定义的平台代码(复制链接) */Bitmap logo = BitmapFactory.decodeResource(getResources(), R.drawable.ssdk_oks_classic_copylink);String label = getString(R.string.ssdk_copyLink);/* 复制链接图标的点击事件 */View.OnClickListener listener = new View.OnClickListener() {@SuppressWarnings("deprecation")public void onClick(View v) {ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);// 将文本内容放到系统剪贴板里。cm.setText(MyConfig.shopUrl + code);ToastXutil.showToast(getApplicationContext(), getString(R.string.language_copiedSuccessfully));}};/* 添加自定义图标 */oks.setCustomerLogo(logo, label, listener);// 启动分享GUIoks.show(this);
}
2.效果展示图片
二、通过要分享到应用的包名的原生分享方式来分享图片,该分享方式是首先把图片保存到本地,再拿保存到本地的图片分享到各个应用
1.保存图片和分享图片
private boolean isShareImage;//是否是分享图片功能
private String packageName = null;//分享平台的一些包名
public void onViewClicked(View view) {switch (view.getId()) {case R.id.fragment_saleAll://保存所有图片isShareImage = false;getPermissions();//獲取權限和保存圖片break;case R.id.fragment_share://分享图片到朋友圈isShareImage = true;shareDirection();break;}}
//获取存储权限private void getPermissions() {// Android6.0以上(包括6.0)系统,不能只是在AndroidManifest.xml中进行配置,// 还要在程序代码中进行动态设置相应的权限。// 版本号if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {// 存储空间权限requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
// requestPermissions(new String[]{Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);} else {saveOrShareImage();}} else {saveOrShareImage();}}// 提示是否獲取權限,获取权限后跳转到二维码扫描界面@Overridepublic void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);switch (requestCode) {case 0:if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {// 取得权限saveOrShareImage();} else {// 未取得权限showToast(getString(R.string.language_noPermissions));}break;}}//保存或分享图片private void saveOrShareImage() {if (isShareImage) {showWaitProgressDialog(getActivity(), 1, getString(R.string.language_pleaseWait));//删除保存分享图片的文件夹和文件ImageCompressUtils.deleteAllFilesOfDir(new File(CommonConstants.shareImagePath));} else {showWaitProgressDialog();}new Thread(saveAllFileRunnable).start();}
//保存所有的图片private Runnable saveAllFileRunnable = new Runnable() {@Overridepublic void run() {try {downloadNum = 0;for (int i = 0; i < listMImage.size(); i++) {if (listMImage.get(i).getMark() == 1) {//只保存已经上传了的所有图片downloadNum++;mBitmap = ImageLoader.getInstance().loadImageSync(listMImage.get(i).getImgPath());SaveImageUtil.saveFile(mBitmap, listMImage.get(i).getImgPath(), getActivity(), isShareImage);}}if (downloadNum >= getServerImage.size()) {if (isShareImage)ShareImage.shareImagesToWeiXin(getActivity(), CommonConstants.shareImagePath, packageName);//分享图片else {mSaveMessage = getString(R.string.language_pictureSavedSuccessfully);}dismissProgressDialog();}} catch (Exception e) {dismissProgressDialog();
// if (isShareImage)
// mSaveMessage = "分享失败,可能沒有存儲空間的權限!";
// else {
// mSaveMessage = getString(R.string.language_pictureSavedFailed);
// }e.printStackTrace();}if (isShareImage == false)messageHandler.sendMessage(messageHandler.obtainMessage());}};private Handler messageHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {showToast(mSaveMessage);}
//选择分享到朋友圈还是朋友
private void shareDirection() {ActionSheet.createBuilder(getActivity(), getActivity().getSupportFragmentManager()).setCancelButtonTitle(getString(R.string.language_dialogNegative)).setOtherButtonTitles(getString(R.string.language_qq), getString(R.string.language_WeChat), getString(R.string.language_weiBo), getString(R.string.language_line), getString(R.string.language_WhatsApp), getString(R.string.language_Facebook)).setCancelableOnTouchOutside(true)//dialog弹出后会点击屏幕,dialog是否消失.setListener(new ActionSheet.ActionSheetListener() {@Overridepublic void onDismiss(ActionSheet actionSheet, boolean isCancel) {}@Overridepublic void onOtherButtonClick(ActionSheet actionSheet, int index) {switch (index) {case 0://QQpackageName = "com.tencent.mobileqq";break;case 1://微信packageName = "com.tencent.mm";break;case 2://微博packageName = "com.sina.weibo";break;case 3://LINEpackageName = "jp.naver.line.android";break;case 4://WhatsAPPpackageName = "com.whatsapp";break;case 5://FacebookpackageName = "com.facebook.katana";break;}if (!ShareImage.isAPPInstalled(getActivity(), packageName))//判断是否安装了相应app,并提示ToastUtils.showToast(getActivity(), getString(R.string.language_noInstalledAPK));elsegetPermissions();//獲取權限和保存圖片后分享到朋友圈}}).show();
}
2.保存图片的方法
/*** 保存圖片的方法*/
public class SaveImageUtil {// 图片保存的文件夹
// private static String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/VIPInternalPicture/";
// private static String path = Environment.getExternalStorageDirectory()
// .getAbsolutePath() + "/VIPInternal/VIPInternalPicture/";//下载图片保存到系统图库private static final String pathImage = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/";//分享到朋友圈的图片保存的地址private static final String shareImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/share_internal_image/";/*** 把图片网址转换为Drawable*/public static Drawable loadImageFromNetwork(String imageUrl) {Drawable drawable = null;try {// 可以在这里通过文件名来判断,是否本地有此图片drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");} catch (Exception e) {Log.d("test", e.getMessage());}
// if (drawable == null) {
// Log.d("test", "null drawable");
// } else {
// Log.d("test", "not null drawable");
// }return drawable;}@SuppressLint("DefaultLocale")public static void saveFile(Bitmap bm, String url, Context context, Boolean isShareImage) throws Exception {String path = null;if (isShareImage)path = shareImagePath;elsepath = pathImage;// 判断sd卡是否存在if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 判断文件夹是否存在File dirFile = new File(path);if (!dirFile.exists()) {dirFile.mkdirs();//创建此抽象路径指定的目录,包括所有必须但不存在的父目录。(及可以创建多级目录,无论是否存在父目录)}String fileName = url.substring(url.lastIndexOf("/") + 1, url.length()).toLowerCase();File file = new File(path + fileName);BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));bm.compress(Bitmap.CompressFormat.PNG, 100, bos);bos.flush();bos.close();
// //把文件插入到系统图库
// MediaStore.Images.Media.insertImage(context.getContentResolver(), bm, fileName, null);// 通知图库更新context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file)));} else {Toast.makeText(context, context.getString(R.string.language_notSDCard), Toast.LENGTH_SHORT).show();}}
}
3.分享图片的方法
/*** 分享图片*/
public class ShareImage {//判断是否安装微信private static boolean isInstallWeChat(Context context) {PackageInfo packageInfo = null;try {packageInfo = context.getPackageManager().getPackageInfo("com.tencent.mm", 0);} catch (Exception e) {packageInfo = null;e.printStackTrace();}if (packageInfo == null)return false;elsereturn true;}//通过包名断是否安装了该程序public static boolean isAPPInstalled(Context context, String packageName) {PackageManager pm = context.getPackageManager();List<PackageInfo> pinfo = pm.getInstalledPackages(0);for (int i = 0; i < pinfo.size(); i++) {if (pinfo.get(i).packageName.equals(packageName)) {return true;}}return false;}/*** 分享图片到微信,分享的是本地图片** @param path 存放图片的地址* @param packageName 要分享到平台的包名*/public static void shareImagesToWeiXin(Context context, String path, String packageName) {try {Intent intent = new Intent("android.intent.action.SEND");intent.setPackage(packageName);//自己选择分享到好友还是朋友圈//直接跳转到LINE选择好友的界面//intent.setComponent(new ComponentName("jp.naver.line.android", "jp.naver.line.android.activity.selectchat.SelectChatActivity"));
// if (isFriends) {
// //com.tencent.mm.ui.tools.ShareImgUI 直接分享到微信好友,
// weChatIntent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI"));
// } else
// //com.tencent.mm.ui.tools.ShareToTimeLineUI 直接分享到微信朋友圈,最多可以分享九张图片到微信朋友圈
// intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI"));intent.setAction(Intent.ACTION_SEND_MULTIPLE);ArrayList<Uri> imageList = new ArrayList();File[] files = new File(path).listFiles();if (files != null) {for (File file : files) {L.e(file.getAbsolutePath());File f = new File(file.getAbsolutePath());if (f.exists()) {if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {//android 7.0以下imageList.add(Uri.fromFile(f));} else {//android 7.0及以上Uri uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(context.getContentResolver(), f.getAbsolutePath(), f.getName(), null));imageList.add(uri);}}}}intent.setType("image/*");intent.putExtra(Intent.EXTRA_STREAM, imageList);
// weChatIntent.putExtra("Kdescription", "aaaa"); //分享描述context.startActivity(intent);} catch (Exception e) {ToastUtils.showToast(context.getApplicationContext(), context.getString(R.string.language_shareFail));}}
}
4.效果图