Android API与Android版本对应关系

Android APIAndroid版本
28Android 9
PAndroid  P Preview
27Android  8.1(Oreo)
26Android  8.0(Oreo)
25Android  7.1.1(Nougat)
24Android  7.0(Nougat)
23Android  6.0(MarshMallow)
22Android  5.1(Lollipop)
21Android  5.0(Lollipop)
20Android  4.4W(Kitkat Wear)
19Android  4.4(Kitkat)
18Android  4.3(Jelly Bean)
17Android  4.2(Jelly Bean)
16Android  4.1(Jelly Bean)
15Android  4.0.3(IceCreamSandwich)
14Android  4.0(IceCreamSandwich)
13Android  3.2(Honeycomb)
12Android  3.1(Honeycomb)
11Android  3.0(Honeycomb)
String fileName = Environment.getExternalStorageDirectory() + File.separator + "test" + File.separator + inputEntity.getUnit() + ".txt";                    
Intent shareIntent = new Intent(Intent.ACTION_SEND);
 //Android7.0版本以上使用FileProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    shareIntent.putExtra(Intent.EXTRA_STREAM,
            FileProvider.getUriForFile(ReviewActivity.this,
            GeneralUtils.getPackageName(ReviewActivity.this)
            + ".provider", new File(fileName)));
 }else {
     shareIntent.putExtra(Intent.EXTRA_STREAM, new File(fileName));
}
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setType("*/*");//此处可发送多种文件
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//这一句一定得写
startActivity(Intent.createChooser(shareIntent, "分享文件"));

 

AndroidManifest.xml中注册.provider.划重点:android:authorities设置成你的包名+(.provider) ,这里的.provider路径要和上面的.provider路径一样android:resource="@xml/provider_paths".这个目录以及文件都是需要自己创建的。

AndroidManifest.xml

<!-- FileProvider配置访问路径,适配7.0及其以上 -->
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.test.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
子节点对应路径例子
files_pathContext.getFilesDir() 
cache_pathContext.getCacheDir() 
external_pathEnvironment.getExternalStorageDirectory()/storage/emulated/0/
external_files_pathContext.getExternalFilesDir() 
externa_cache_pathContext.getExternalCacheDir() 

@xml/provider_paths

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="test/"/>
</paths>

我的文件路径是Environment.getExternalStorageDirectory() ,所以paths子节点name是external_path. path = "test"是你文件存放的路径,/storage/emulated/0/是虚拟目录,实际上的路径是手机存储/test/xxx.txt。

路径没写对,分享的时候会报“获取资源失败”。

以上就是使用系统的分享文件到各平台的方法。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐