我使用FileProvider来分享我的应用程序的图像。虽然它非常适合通过 gmail、环聊、驱动器等进行文件共享,但我无法通过非 Google 应用程序共享文件,例如 WhatsApp、Viber。
Androidmanifest中的 FileProvider
<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>
文件路径.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();
}
}