分享图片到第三方应用(微信)时,正常调用代码:
Uri uri=getFileUri(context,"文件全路径不包含文件名","文件名包含扩展名");
Intent intent = new Intent();
ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");
intent.setComponent(comp);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(intent, "发送到"));
下面解析下Uri怎么获取
public static Uri getFileUri(Context context, String path, String name) {
Uri mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//先去媒体库查询这张图片,看是否存在
Cursor cursor = context.getContentResolver().query(mediaUri,
null,
MediaStore.Images.Media.DISPLAY_NAME + "= ?",
new String[]{name}, null);
Uri uri = null;
if (cursor != null && cursor.moveToFirst()) {//存在,直接获取这个uri
uri = ContentUris.withAppendedId(mediaUri,
cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
cursor.close();
} else {//不存在,
String fileStr = path + File.separator + name;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
File file = new File(fileStr);
//这时需要生成一张图片插入到图库再创建uri
uri =
Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), name, null));
} catch (FileNotFoundException e) {
Toast.makeText(context, "图片不存在", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else {
uri = Uri.fromFile(new File(fileStr));
}
}
return uri;
}
*上面有点小坑,网上大部分教程只有从注释“不存在”的位置开始,没有上面判断图库是否存在的那一步,
当图库已存在这张图片时,这样分享会导致分享完成后图库在系统的picture文件夹创建一张同样的缩略图,自然而然 分享出去的也是那张缩略图,不是原图,
当你分享gif动图时,你分享出去的就不是原图了,只是一张缩略图,根本不会动;
当不存在这张图片时,就需要先更新图库再发送,这样就能保证原图分享;
这是本人找到的一种办法,测试没有问题;