有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么这个共享图像不适用于所有的移动设备?

共享图像代码 我想找到一个代码的例子,它将允许我通过Android Intent,ACTION_SEND共享一个与最多Android设备兼容的图像

我的代码如下所示:

  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);
    }

目前,这段代码不适用于所有移动设备,只适用于一些移动设备,尤其是安卓版本为6.0 7.0 7.1 8.0的设备,我不知道这段代码是否正确

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


共 (1) 个答案

  1. # 1 楼答案

    如果targetSdkVersion高于24,则使用FileProvider授予访问权限

    创建一个名为provider_path的xml文件。xmlres\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
            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"));
            }