分享应用中的文件给其它应用

使用FileProvider把本应用的文件分享给其它应用。

第一步:
在res目录下建立一个xml文件夹,然后在res/xml/下建立file_paths.xml。
file_paths.xml中的内容:
<?xml version="1.0" encoding="utf-8"?>
<Paths xmlns:android="http://schemas.android.com/apk/res/android">
<cache-path name="my_images" path="images/"/>
<cache-path name="my_docs" path="docs/"/>
</Paths>
其中:其中的cache-path也可以是files-path或者external-path。cache-path对应第三步中的this.getCacheDir,files-path对应this.getFilesDir(),external-path对应Environment.getExternalStorageDirectory()。

第二步:
在AndroidManifest.xml中加入:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.zfeng.stackquesprovider.cachefile"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
其中:android:authorities属性是你想让FileProvider生成的URI;android:exported属性表示本Provider是否对其它应用可见;android:grantUriPermissions属性当设为true时授权给所有content provider数据,如果为false授权给<grant-uri-permission>中列出的数据。 通过meta-data引入file_paths.xml。

第三步:
在Activity文件中,加入以下控制代码:
用FileProvider.getUriForFile(this, MainActivity.Authority, fileImage)得到的Uri为content://com.zfeng.stackquesprovider.cachefile/my_images/image.png,因为<cache-path name="my_images" path="images/"/>。
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.image);

File file=new File(this.getCacheDir(),"images");
file.mkdirs();
File fileImage=new File(file,"image.png");
OutputStream fos=null;
try{
fos = new FileOutputStream(fileImage);
bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
}catch (Exception e)
{
e.printStackTrace();
}finally{
if(fos!=null)
{
try{fos.close();}catch(Exception e){e.printStackTrace();}
}
}

// Uri contentUri = FileProvider.getUriForFile(this, MainActivity.Authority, fileImage);
Uri contentUri = Uri.parse("content://com.zfeng.stackquesprovider.cachefile/my_images/image.png");

if (contentUri != null) {

Log.d(MainActivity.TAG,"contentUri="+contentUri.toString());

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file
shareIntent.setDataAndType(contentUri, getContentResolver().getType(contentUri));
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
startActivity(Intent.createChooser(shareIntent, "Choose an app"));
}

你可能感兴趣的:(分享应用中的文件给其它应用)