我使用FileProvider分享我的应用图片。虽然它非常适合通过gmail,环聊,驱动器等进行文件共享,但我无法通过非谷歌应用程序共享文件,即WhatsApp,Viber。
Androidmanifest中的 <provider
android:name="android.support.v4.content.FileProvider"
android:authorities="<package.name>.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
filepath.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path path="" name="export" />
</paths>
共享文件的方法
/**
* Static method to export charts data
*
* @param mContext object context
* @param view chart to be converted into image
* @throws IOException
**/
public static void exportChartAsPng(Context mContext, View view) throws IOException {
File baseDir = mContext.getFilesDir();
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String fileName = "chart-" + df.format(calendar.getTimeInMillis()) + ".png";
String filePath = baseDir.toString() + File.separator + fileName;
File chartFile = new File(filePath);
OutputStream outStream = new FileOutputStream(chartFile);
getBitmapFromView(view).compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
try {
Uri fileUri = FileProvider.getUriForFile(
mContext,
"<package.name>.fileprovider",
chartFile);
Intent sendIntent = new Intent("<package.name>.ACTION_RETURN_FILE");
if (fileUri != null) {
// Grant temporary read permission to the content URI
sendIntent.addFlags(
Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
sendIntent.setType("image/png");
mContext.startActivity(Intent.createChooser(sendIntent, mContext.getString(R.string.share)));
} catch (IllegalArgumentException e) {
Log.e("File Selector",
"The selected file can't be shared: " +
chartFile.getName());
e.printStackTrace();
}
}