android - 调用系统分享功能分享图片

 

step1: 编写分享代码, 将Uri的生成方式改为由FileProvider提供的临时授权路径,并且在intent中添加flag 

注意:在Android7.0之后,调用系统分享,传入URI的时候可能会导致程序闪退崩溃。这是由于7.0的新的文件权限导致的。下面的代码对其做了处理

public static int sharePic(Context context, String picFilePath) {
        File shareFile = new File(picFilePath);
        if (!shareFile.exists()) return SHARE_RESULT_FILE_NOT_FOUND;
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName()+".flightlog.fileprovider", shareFile);
            intent.putExtra(Intent.EXTRA_STREAM, contentUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }else {
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(shareFile));
        }
        intent.setType(MIME_TYPE_IMAGE);
        Intent chooser = Intent.createChooser(intent, context.getString(R.string.flight_log_dialog_share_title));
        if(intent.resolveActivity(context.getPackageManager()) != null){
            context.startActivity(chooser);
        }
        return SHARE_RESULT_NO_ERROR;
    }

step2: 在 AndroidManifest.xml 中的 application 标签中添加 provider 的配置

<application
       ...>
         <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.yongdaimi.android.fileprovider"//注意和上面FileProvider方法中声明的authorities保持一致
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths_share_img" />
        </provider>
    </application>

注意: provider 标签中 name 属性和 authorities 声明的值是有可能与第三方库冲突的,可酌情修改。

step3: 在res/xml中新建一个文件 file_paths_share_img.xml 

<?xml version="1.0" encoding="utf-8"?>
<resource xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="images"
        path="DCIM/IMAGE" />
</resource>

参考链接:

FileProvider使用及相关第三方冲突的完美解决

 

转载于:https://www.cnblogs.com/yongdaimi/p/10287477.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值