android 调用系统api 打开或者分享文件

223 阅读1分钟
val intent = Intent()
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//设置intent的Action属性
intent.action = Intent.ACTION_SEND
// 1 注意点1 
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
intent.flags = Intent.FLAG_GRANT_WRITE_URI_PERMISSION;
//获取文件file的MIME类型
val type: String = FileDeleteUtils.getMimeType(file)
//设置intent的data和Type属性。
val uri = if(Build.VERSION.SDK_INT >= 24){
    FileProvider.getUriForFile(context, context.packageName + ".fileprovider", file)
}else {
    Uri.fromFile(file)
}
// 2 注意点2
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setDataAndType(uri,type)
//跳转
context.startActivity(intent) 
private static String getSuffix(File file) {
    if (file == null || !file.exists() || file.isDirectory()) {
        return null;
    }
    String fileName = file.getName();
    if (fileName.equals("") || fileName.endsWith(".")) {
        return null;
    }
    int index = fileName.lastIndexOf(".");
    if (index != -1) {
        return fileName.substring(index + 1).toLowerCase(Locale.US);
    } else {
        return null;
    }
}

public static   String getMimeType(File file){
    String suffix = getSuffix(file);
    if (suffix == null) {
        return "file/*";
    }
    String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix);
    if (type != null || !type.isEmpty()) {
        return type;
    }
    return "file/*";
}
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepaths"
        />
</provider>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    /*这个tag 有很多 分别代表不同的位置 百度*/
    /* path 设置 . 代表当前文件夹下的所有子目录都可以访问 */
    <external-path name="external" path="."/>
</paths>