備注:
①.這個不用導(dǎo)入微信的jar和注冊微信的APP_ID 陶珠。
②. 實際上分享時是調(diào)用系統(tǒng)本地的分享功能括袒,所以分享的圖片必須要保存到本地。
③. 保存到本地是耗時操作 分享的代碼需要在子線程執(zhí)行 扛邑。
分享
1.分享到微信好友
// 圖片地址List
final List<String> urlList= new ArrayList<>();
// 圖片F(xiàn)ile
final List<File> files = new ArrayList<>();
for (int i = 0; i < urlList.size(); i++) {
//網(wǎng)絡(luò)圖片保存到本地
File file = Util.saveImageToSdCard(getContext(), urlList.get(i));
files.add(file);
}
//分享的圖片集合
ArrayList<Uri> imageUris = new ArrayList<Uri>();
for (File f : files) {
imageUris.add(Uri.fromFile(f));
}
//分享到微信好友
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, imageUris);
startActivity(intent);
2.分享到微信朋友圈
// 圖片地址List
final List<String> urlList= new ArrayList<>();
// 圖片F(xiàn)ile
final List<File> files = new ArrayList<>();
for (int i = 0; i < urlList.size(); i++) {
//網(wǎng)絡(luò)圖片保存到本地
File file = Util.saveImageToSdCard(getContext(), urlList.get(i));
files.add(file);
}
//分享的圖片集合
ArrayList<Uri> imageUris = new ArrayList<Uri>();
for (File f : files) {
imageUris.add(Uri.fromFile(f));
}
//分享到微信朋友圈
Intent weChatIntent = new Intent();
weChatIntent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI"));
if (imageUris.size() == 0) return;
weChatIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
weChatIntent.setType("image/*");
weChatIntent.putExtra(Intent.EXTRA_STREAM, imageUris);
weChatIntent.putExtra("kdescription", data.get(i).Content.trim()); //分享描述
getContext().startActivity(weChatIntent);
補充 Util.saveImageToSdCard 代碼
public static String IMAGE_NAME = "iv_share";
public static int i =0;
//根據(jù)網(wǎng)絡(luò)圖片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;
}
}
//創(chuàng)建本地保存路徑
public static File createStableImageFile(Context context) throws IOException {
i++;
String imageFileName =IMAGE_NAME + i+ ".jpg";
File storageDir = context.getExternalCacheDir();
File image = new File(storageDir, imageFileName);
return image;
}