產品需求:
微信分享多圖至好友,朋友圈。由於微信禁用了分享9圖至朋友圈功能,這里分享微信只是將圖片保存至本地,具體讓用戶手動分享。
問題分析:
微信沒有提供分享多圖的SDK,因此我們實現調用系統自帶的分享功能。將分享的圖片保存至本地,再調用系統本地的分享實現分享多圖操作。
具體實現:
這里保存圖片實現用了兩種方式:
- 使用網絡請求下載圖片。
- 使用Glide加載圖片。
2.1 將請求網絡的圖片轉化成bitmap,再將bitmap圖片保存至本地相冊。
2.2 獲取緩存至本地的文件,再將文件保存至指定目錄,更新相冊。
注意:保存圖片至系統相冊目錄時,只能在主線程實現。推斷里面使用了IO流的原因。
一、分享多圖至微信
AtomicInteger count = new AtomicInteger(); ArrayList<Observable<File>> observables = new ArrayList<>(); List<Uri> imageUris = new ArrayList<Uri>(); mCommitDialog = WeiboDialogUtils.createLoadingDialog(this, "正在加載..."); observables.add(Observable.fromIterable(imageList).flatMap(new Function<String, ObservableSource<File>>() { @Override public ObservableSource<File> apply(String imagePath) throws Exception { return Observable.create(new ObservableOnSubscribe<File>() { @Override public void subscribe(ObservableEmitter<File> emitter) throws Exception { File file = PhotoUtils.saveImageToSdCard(getActivity(), imagePath); emitter.onNext(file); } }); } }).subscribeOn(Schedulers.io())); Observable.merge(observables).map(new Function<File, Boolean>() { @Override public Boolean apply(File f) throws Exception { File file = new File(f.getAbsolutePath()); if(file.exists()) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {//android 7.0以下
imageUris.add(Uri.fromFile(file)); } else {//android 7.0及以上
Uri uri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), null)); imageUris.add(uri); } return true; } return false; }}).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean a) throws Exception { if(a) count.addAndGet(1); if(imageList.size() == count.get()){ mCommitDialog.dismiss(); // showMessage(R.string.text_share_success ); //分享到微信好友
Intent intent = new Intent(); ComponentName componentName = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI"); if (imageUris.size() == 0) return; intent.setComponent(componentName); intent.setAction(Intent.ACTION_SEND_MULTIPLE); intent.setType("image/*"); intent.putExtra(Intent.EXTRA_STREAM, (Serializable) imageUris); startActivity(intent); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { mCommitDialog.dismiss(); showMessage(R.string.text_save_failed); } }, new Action() { @Override public void run() throws Exception { } }) ;
saveImageToSdCard方法如下。
//根據網絡圖片url路徑保存到本地
public static final File saveImageToSdCard(Context context, String image) { boolean success = false; File file = null; try { file = createStableImageFile(context); Bitmap bitmap = null; URL url = new URL(image); HttpURLConnection conn = null; conn = (HttpURLConnection) url.openConnection(); InputStream is = null; is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); FileOutputStream outStream; outStream = new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); outStream.close(); success = true; } catch (Exception e) { e.printStackTrace(); } if (success) { return file; } else { return null; } }
二、保存多圖至本地。
1.Glide加載圖片生成Bitmap對象。
AtomicInteger count = new AtomicInteger(); ArrayList<Observable<Boolean>> observables = new ArrayList<>(); for (String imagePath : imageList) { observables.add(Observable.create(new ObservableOnSubscribe<Boolean>() { @Override public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception { SimpleTarget<Bitmap> into = Glide.with(getActivity()) .asBitmap() .load(imagePath) .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady( Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) { if (bitmap != null) { //圖片信息不為空時才保存 emitter.onNext( PhotoUtils.savePhoto(getActivity(), DateUtils.formatDate(getActivity(), System.currentTimeMillis()) + UUID.randomUUID() + ".png", bitmap)); } } }); } }).subscribeOn(AndroidSchedulers.mainThread()));} Observable.merge(observables).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean b) throws Exception { if (b) { count.addAndGet(1); } if(imageList.size() == count.get()){ showHintDialog(); // showMessage(R.string.text_save_pic_success ); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { showMessage(R.string.text_save_pic_failed); } }, new Action() { @Override public void run() throws Exception { } });
2.Glide加載圖片,得到文件形式。
File file = Glide.with(context)
.load(images[i])
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get()
savePhoto方法如下:
/** * 保存圖片 */ public static boolean savePhoto(Context context, String fileName, Bitmap bitmap) { //系統相冊目錄 String galleryPath = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator + "Camera" + File.separator; File imagePath = new File(galleryPath); if (!imagePath.exists()) { imagePath.mkdirs(); } File fileUri = new File(imagePath + File.separator + fileName); if (!fileUri.exists()) { try { fileUri.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } Uri imgUri = Uri.fromFile(fileUri); try { FileOutputStream out = new FileOutputStream(fileUri); bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(imgUri); context.sendBroadcast(intent); return true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; }
注意:這里要申請權限。
參考博客: