Android 分享图片、gif 到微信等第三方应用

分享图片到第三方应用(微信)时,正常调用代码:

    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动图时,你分享出去的就不是原图了,只是一张缩略图,根本不会动;

当不存在这张图片时,就需要先更新图库再发送,这样就能保证原图分享;

这是本人找到的一种办法,测试没有问题;

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值