首页 > 解决方案 > 为什么此共享图像仅适用于所有移动设备?

问题描述

共享图像代码 我想找到一个代码示例,它允许我通过与最多 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的设备,我不知道此代码是否正确。

我希望这样的代码适用于所有设备。

标签: javaandroidimageshare

解决方案


如果 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"));
        }

推荐阅读