Android使用系统分享文件给微信,QQ指定的用户

                                                              Android API与Android版本对应关系

Android API Android版本
28 Android 9
P Android  P Preview
27 Android  8.1(Oreo)
26 Android  8.0(Oreo)
25 Android  7.1.1(Nougat)
24 Android  7.0(Nougat)
23 Android  6.0(MarshMallow)
22 Android  5.1(Lollipop)
21 Android  5.0(Lollipop)
20 Android  4.4W(Kitkat Wear)
19 Android  4.4(Kitkat)
18 Android  4.3(Jelly Bean)
17 Android  4.2(Jelly Bean)
16 Android  4.1(Jelly Bean)
15 Android  4.0.3(IceCreamSandwich)
14 Android  4.0(IceCreamSandwich)
13 Android  3.2(Honeycomb)
12 Android  3.1(Honeycomb)
11 Android  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_path Context.getFilesDir()  
cache_path Context.getCacheDir()  
external_path Environment.getExternalStorageDirectory() /storage/emulated/0/
external_files_path Context.getExternalFilesDir()  
externa_cache_path Context.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。

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

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

发布了23 篇原创文章 · 获赞 11 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/u014095878/article/details/103048841