java - 为什么此共享图像仅适用于所有移动设备?
问题描述
共享图像代码 我想找到一个代码示例,它允许我通过与最多 Android 设备兼容的 Android Intent、ACTION_SEND 共享图像。
我的代码如下所示:
public void onClickShare(View view) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(SavedCardActivity.sharingcardpath)));
startActivityForResult(Intent.createChooser(intent, "Share"), 1);
}
目前,此代码不适用于所有移动设备,仅适用于部分移动设备,尤其是 android 版本为 6.0 7.0 7.1 8.0的设备,我不知道此代码是否正确。
我希望这样的代码适用于所有设备。
解决方案
如果 targetSdkVersion 高于 24,则使用 FileProvider 授予访问权限。
在res\xml中创建一个名为provider_paths.xml的 xml 文件,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
然后你需要在你的应用标签内的 AndroidManifest.xml 中添加一个 Provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
现在得到你的照片路径是这样的:
final File photoFile = new File(Environment.getExternalStorageDirectory().toString(), "/path/filename.png");
现在像这样获取照片 URI:
Uri photoURI = FileProvider.getUriForFile(SavedCardActivity.this,
BuildConfig.APPLICATION_ID + ".provider",
photoFile);
要分享,请使用以下代码:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
getApplicationContext().startActivity(Intent.createChooser(shareIntent, "Share image using"));
} else {
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
推荐阅读
- firebase - 尽管已登录,但在查询 Firestore 时,Firebase 身份验证为空
- postgresql - 函数内的时间戳比较
- php - 在 PHP 中重新格式化字符串以添加双引号和反斜杠
- c - 如何停止接收输入与 C 中的输入
- css - 如何让一个内部带有可滚动 div 的 div 不会根据窗口大小滚动超过某个点?
- pandas - 从数据框中删除一组日期
- java - java.security.UnrecoverableKeyException:获取密钥失败:AES SecretKeyFactory 不可用
- mysql - 用于检索具有最多幻影数量的列组合的 SQL 查询
- ios - dart:ffi 用于 NSURLSession
- loops - 批处理脚本,检查文件夹是否存在在循环内失败