如何从android marshmallow中的图库中获取图像?

时间:2017-03-01 13:29:28

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

您好我在app工作,用户可以在注册帐户时选择图像。我能够在棒棒糖上获得图像,但是当我在棉花糖中测试它时,我没有得到文件及其名称,我可以向用户请求许可,当我从图库中选择图像时,我没有得到任何文件或其名称

这是我的代码

        select_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Build.VERSION.SDK_INT >=23) {
                    if (checkPermission()){
                        Intent intent = new Intent();
                        intent.setType("*/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);

                    }else{
                        requestPermission();
                    }
                }else{
                    Intent intent = new Intent();
                    intent.setType("*/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);

                }
            }

        });

My Permissions

private boolean checkPermission() {
    int result = ContextCompat.checkSelfPermission(Register.this, Manifest.permission.READ_EXTERNAL_STORAGE );
    if (result == PackageManager.PERMISSION_GRANTED) {
        return true;
    } else {
        return false;
    }
}


private void requestPermission() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(Register.this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
        Toast.makeText(Register.this, "Write External Storage permission allows us to access images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
    } else {
        ActivityCompat.requestPermissions(Register.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }
}

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        if(requestCode == PERMISSION_REQUEST_CODE){
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(this, "Accepted", Toast.LENGTH_SHORT).show();


                Intent intent = new Intent();
                 intent.setType("*/*");
                 intent.setAction(Intent.ACTION_GET_CONTENT);
                  startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);





                } else {
                    Log.e("value", "Permission Denied, You cannot use local drive .");
                }
        }

    }

选择图像后

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {

            filePath = data.getData();
            if (null != filePath) {
                try {

                    bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
                    // img.setImageBitmap(bitmap);

                    if (filePath.getScheme().equals("content")) {
                        try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
                            if (cursor != null && cursor.moveToFirst()) {
                                file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
                                img_name.setText(file_name);
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

我不知道为什么它不在棉花糖中工作,即使我已经给予了许可

3 个答案:

答案 0 :(得分:2)

我解决了。

   public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {

                filePath = data.getData();
                if (null != filePath) {
                    try {

                        bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), filePath);
                        // img.setImageBitmap(bitmap);

                        if (filePath.getScheme().equals("content")) {
                            try (Cursor cursor = getContentResolver().query(filePath, null, null, null, null)) {
                                if (cursor != null && cursor.moveToFirst()) {
                                    file_name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                                    Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();
                                    img_name.setText(file_name);
                                }
                            }
                        }else {

                            String path= data.getData().getPath();
                            file_name=path.substring(path.lastIndexOf("/")+1);
                            img_name.setText(file_name);
                            Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

当我选择文件时,我没有达到这个条件

 if (filePath.getScheme().equals("content"))

所以在其他情况下我已经给出了这个

 String path= data.getData().getPath();
                            file_name=path.substring(path.lastIndexOf("/")+1);
                            img_name.setText(file_name);
                            Toast.makeText(this, file_name, Toast.LENGTH_SHORT).show();

答案 1 :(得分:1)

要从任何api级别的图库中获取图片,请按照以下步骤操作:

将所有4项功能复制并粘贴到您的活动中 并调用此方法打开图库 galleryPermissionDialog();

使用变量

final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
protected static final int REQUEST_CODE_MANUAL = 5;

需要添加低于棉花糖的权限

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

功能1:

void openGallry() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, 1);
    }

功能2:

void galleryPermissionDialog() {

    int hasWriteContactsPermission = ContextCompat.checkSelfPermission(ActivityProfile.this,
            android.Manifest.permission.READ_EXTERNAL_STORAGE);
    if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(ActivityProfile.this,
                new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_CODE_ASK_PERMISSIONS);
        return;

    } else {
        openGallry();
    }
}

功能3:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ASK_PERMISSIONS: {
            Map<String, Integer> perms = new HashMap<String, Integer>();
            // Initial
            perms.put(android.Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
            // Fill with results
            for (int i = 0; i < permissions.length; i++)
                perms.put(permissions[i], grantResults[i]);
            // Check for READ_EXTERNAL_STORAGE

            boolean showRationale = false;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                if (perms.get(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    // All Permissions Granted
                    galleryPermissionDialog();
                } else {
                    showRationale = ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE);
                    if (showRationale) {
                        showMessageOKCancel("Read Storage Permission required for this app ",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        galleryPermissionDialog();

                                    }
                                });
                    } else {
                        showMessageOKCancel("Read Storage Permission required for this app ",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Toast.makeText(ActivityProfile.this, "Please Enable the Read Storage permission in permission", Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                                        intent.setData(uri);
                                        startActivityForResult(intent, REQUEST_CODE_MANUAL);
                                    }
                                });

                        //proceed with logic by disabling the related features or quit the app.
                    }


                }


            } else {
                galleryPermissionDialog();

            }

        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

功能4:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch (requestCode) {
        case 1:
            if (resultCode == RESULT_OK) {
                try {
                    final Uri imageUri = imageReturnedIntent.getData();
                   /* final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                    img_profile.setImageBitmap(selectedImage);*/
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    pictureFile = saveBitmapToFile(new File(picturePath));
                    Picasso.with(getApplicationContext()).load(new File(picturePath)).transform(new CircleTransform()).into(imgProfile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    }
}

功能5:

public void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
    new AlertDialog.Builder(ActivityProfile.this)
            .setTitle(R.string.app_name)
            .setMessage(message)
            .setCancelable(false)
            .setPositiveButton("OK", okListener)
            .setNegativeButton("Cancel", null)
            .create()
            .show();
}

答案 2 :(得分:0)

file / *不是有效的MIME类型。如果要支持任何类型的文件,则应使用 / 。您看到的文件无法选择,因为它们的MIME类型不正确。

随着Android 7.0中的虚拟文件的引入(没有字节流的文件,因此无法直接上传),您最好将CATEGORY_OPENABLE添加到您的Intent:

https://developer.android.com/about/versions/nougat/android-7.0.html#virtual_files

https://developer.android.com/reference/android/content/Intent.html#CATEGORY_OPENABLE

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    //sets the select file to all types of files
    intent.setType("*/*");
    // Only get openable files
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    //starts new activity to select file and return data
    startActivityForResult(Intent.createChooser(intent,
            "Choose File to Upload.."), PICK_FILE_REQUEST);
}


public String getFileName(Uri uri) {
    String result = null;
    if (uri.getScheme().equals("content")) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
        } finally {
            cursor.close();
        }
    }
    if (result == null) {
        result = uri.getPath();
        int cut = result.lastIndexOf('/');
        if (cut != -1) {
            result = result.substring(cut + 1);
        }
    }
    return result;
}

String filename = getFileName(yourfileuri);