覆盖选择器意图行为

时间:2016-09-30 09:25:28

标签: android android-intent permissions android-6.0-marshmallow

在我的应用程序中,当用户按下“ImageView”时,我正在创建一个选择器意图,以促使用户更改图片。

以下是用户点击ImageView时使用的代码

userProfileIMG.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            photoPickerIntent.setType("image/*");

            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePhotoIntent.resolveActivity(getPackageManager()) != null)
            {
                try
                {
                    photoFile = Create_ImageFile();
                }
                catch (Exception e)
                {
                    Log.e("file", e.toString());
                }
                if (photoFile != null)
                {
                    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile()));
                }
            }

            String pickTitle = getString(R.string.select_or_take_new_picture);
            Intent chooserIntent = Intent.createChooser(photoPickerIntent, pickTitle);
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{takePhotoIntent});

            startActivityForResult(chooserIntent, ACTIVITY_SELECT_PICTURE);
        }
    });

这是结果

enter image description here

我的问题是,当用户按下“图库”并在6.0上选择图像时会给出安全例外,因为我只想在按下“图库”时请求<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>是否有任何方法可以覆盖行为当用户按“画廊”以便我请求许可时,如果他授予我让他继续到画廊,否则我否认他? 或者我必须手动构建相同的选择器,而不是根据系统为我构建对话框?

1 个答案:

答案 0 :(得分:0)

在Android 6.0及更高版本中编写和读取外部存储需要动态请求权限。这是android 6.0以后引入的一个特殊功能[Marshmallow]。

虽然你声明了

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在android清单中,当在android 6.0中运行时,将检查是否有权限为您的应用程序写入外部存储。 [请参阅设置中的应用权限详细信息 - &gt;应用 - &gt; youapp - &gt;权限。如果它被禁用,您可能面临崩溃。

有关详细信息,请查看android developer portal

另请参阅以下帖子,以便您了解。

Storage permission error in Marshmallow

Android 6.0 Marshmallow. Cannot write to SD Card

更新:通过意图访问还需要实现权限系统。 Image from Gallery in Android 6(Marshmallow)

让我知道查询。