问题1:我有一个pdf存储在
中Environment.getExternalStorageDirectory() --> /storage/emulated/0/appname/downloads/sample.pdf
我正在使用正常方式发送它,如下所示:
File iconsStoragePath = Environment.getExternalStorageDirectory();
final String selpath = iconsStoragePath.getAbsolutePath() + "/appname/downloads/";
Intent intent = new Intent(Intent.ACTION_SEND);
Uri selectedUri = Uri.parse(selpath + "/" + item.getFilename());
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
intent.setType(mimeType);
intent.putExtra(Intent.EXTRA_STREAM, selectedUri);
startActivity(Intent.createChooser(intent, "Share File"));
现在结果是
问题是文件没有文件名共享。
问题2:当我尝试使用文件提供程序时,pdf不共享会给我一个错误:
无法分享。请再试一次
Environment.getFilesDir() --> /data/data/com.myapp.name/files/myapp/downloads/sample.pdf
清单文件:
<application>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/nnf_provider_paths" />
</provider>
</application>
XML / nnf_provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<files-path
name="root"
path="myapp/downloads" />
代码:
File path = new File(getFilesDir(), "downloads");
File file = new File(documentsPath + "/" + filename);
Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), AUTHORITY, file);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, contentUri);
intent.setType("application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
哪种方式更好?
答案 0 :(得分:1)
我个人更喜欢#2。阅读this有关如何使用ShareCompat
创建ShareIntents
关于方法#2的问题,我猜你错过了.setData
或.setDataAndUri
:
这是一个示例代码段,可供我通过FileProviders
分享图片:
public static void shareImage(Activity context) {
Log.d(TAG, "initializing share image");
File imgPath = new File(context.getCacheDir(), DEFAULT_TEMP_DIR_NAME);
File newFile = new File(imgPath, DEFAULT_TEMP_FILENAME);
String authority = context.getPackageName() + ".fileprovider";
Log.d(TAG, "authority: " + authority);
Uri contentUri = FileProvider.getUriForFile(context, authority, newFile);
if (contentUri != null) {
Intent shareIntent = ShareCompat.IntentBuilder.from(context)
.setType("image/png")
.setStream(contentUri)
.setSubject(context.getString(R.string.share_subject))
.setText(context.getString(R.string.share_message))
.setEmailTo(new String[]{"example@example.com"})
.getIntent();
shareIntent.setData(contentUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(Intent.createChooser(
shareIntent, context.getString(R.string.share_chooser_title)));
}
}