android笔记-7.0App间共享文件

来源:互联网 发布:mysql add user 编辑:程序博客网 时间:2024/05/21 05:19

将一个app内文件在另一个打开,在以前几行代码,7.0之后,烦人了。。。

一、AndroidManifest文件中注册

<provider            android:name="android.support.v4.content.FileProvider"            android:authorities="applicationId.FileProvider"            android:exported="false"            android:grantUriPermissions="true">            <meta-data                android:name="android.support.FILE_PROVIDER_PATHS"                android:resource="@xml/path"/></provider>
authorities:FileProvider控制域,build.gradle中applicationId的值+“.FileProvider”

exported:FileProvider是否需要公开

grantUriPermissions:是否授予文件临时访问权限

二、在资源文件夹res文件夹下创建xml文件夹,并在其中新建file:path

<resources>    <paths>        <external-path name="name" path=""></external-path>    </paths></resources>
path:共享文件所在根目录那个文件夹下,如path=“text/”,则表示/storage/emulated/0/text路径下文件,空值表示根目录下,这样能访问所有文件
三、在代码中实现跳转
                    Uri uri = null;                    if (Build.VERSION.SDK_INT >= 24) {                        uri = FileProvider.getUriForFile(ShowExcelActivity.this, "applicationId.FileProvider",file);                    } else {                        uri = Uri.fromFile(file);                    }                    Intent intent = new Intent(Intent.ACTION_VIEW);                    intent.addCategory(Intent.CATEGORY_DEFAULT);                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                    intent.setDataAndType(uri, "application/vnd.ms-excel");                    startActivity(intent);

FileProvider.getUriForFile(context,authority,file)authority需要和清单配置文件中注册的provider中authorities的值一样

intent.addFlags(Intent.FLAG_CRANT_READ_URI_PERMISSION)这句话可能是赋予其它app操作文件的权限,如果不在清单文件中注册,7.0以上手机运行此逻辑会崩溃,如果注册了不加这句话,能打开三方app,但是比如是带文件跳转,则三方app不会像预期那样直接打开文件。

原创粉丝点击