AndroidN(7.0)跨应用访问适配

上一篇文章已经写过安卓7.0跨应用的访问方法,这篇文章主要记录访问相机以及文件方法;


  • 首先在AndroidManifest.xml中声明(必须在application标签内):
        <!--适配安卓N跨应用访问-->
        <provider
            android:authorities="com.example.reportwork.fileprovider"
            android:name="android.support.v4.content.FileProvider"
            android:grantUriPermissions="true"
            tools:replace="android:authorities"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
  • 在资源文件中新建XML文件夹并新建xml文件(file_paths.xml):

    XML

<paths>
    <!-- root-path 从最底层目录开始 -->
    <root-path path="" name="reportwork" />
</paths>
//getFilesDir()
<files-path name="name" path="path" />

//getCacheDir()
<cache-path name="name" path="path" />

//Environment.getExternalStorageDirectory()
<external-path name="name" path="path" />

//getExternalFilesDir()
<external-files-path name="name" path="path" />

//getExternalCacheDir()
<external-cache-path name="name" path="path" />

如果你不知道用什么,则直接使用root-path即可,代表从最底层根目录开始;

//打开文件
    public static void openFile(Context context, File file, String contentType) throws ActivityNotFoundException {
        if (context == null) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setDataAndType(getUriForFile(context, file), contentType);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

//打开相机
    public static void openCamera(Activity activity, File file, int requestCode) {
        if (activity == null) {
            return;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getUriForFile(activity, file));
        activity.startActivityForResult(intent, requestCode);
    }

    private static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= 24) {
            uri = FileProvider.getUriForFile(context, "包名+.fileprovider", file);
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值