简体   繁体   English

如何从Android棉花糖中的画廊获取图像?

[英]How to get image from gallery in android marshmallow?

Hi i am working in app were user can select image when he is registering an account. 嗨,我在应用程序中工作,当时用户可以在注册帐户时选择图片。 I am able to get image on lollipop but when i am testing it in marshmallow then i am not getting file and its name, I am able to ask permission from user and when i am selecting image from gallery i am not getting any file or its name 我能够在棒棒糖上获取图像,但是当我在棉花糖中对其进行测试时,我没有获取文件及其名称,我可以征求用户的许可,当我从图库中选择图像时,我没有任何文件或其获取内容名称

This is my Code 这是我的密码

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

    }

After Selecting Image 选择图像后

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

I am not getting why its not working in marshmallow even i have given permissions 我不明白为什么即使我有权限也不能在棉花糖中使用

I solved it. 我解决了

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

When i was selecting file , then i was not going to this condition 当我选择文件时,我就不会进入这种情况

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

so in else condition i have given this 所以在其他情况下我给了这个

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

To get image from gallery on any api level then follow this : 要从任何API级别的图库中获取图像,请按照以下步骤操作:

Copy and paste all 4 function to your activity And call this to open gallery galleryPermissionDialog(); 将所有4个函数复制并粘贴到您的活动中,并调用它来打开gallery galleryPermissionDialog();。

Variable used 使用变量

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

Permission need to add for lower than marshmallow 低于棉花糖的权限需要添加

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

Function 1: 功能一:

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

Function 2 : 功能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();
    }
}

Function 3 : 功能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);
    }
}

Function 4 : 功能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();
                }
            }
    }
}

Function 5 : 功能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();
}

file/* is not a valid MIME type. file / *不是有效的MIME类型。 You should use / if you want to support any type of file. 如果要支持任何类型的文件,则应使用/ The files you see are unselectable because they are not of the correct MIME type. 您看到的文件是不正确的,因为它们不是正确的MIME类型。

With the introduction of virtual files in Android 7.0 (files that don't have a bytestream and therefore cannot be directly uploaded), you should most definitely add CATEGORY_OPENABLE to your Intent: 随着Android 7.0中引入虚拟文件(没有字节流因此无法直接上传的文件),您绝对应该将CATEGORY_OPENABLE添加到Intent中:

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

https://developer.android.com/reference/android/content/Intent.html#CATEGORY_OPENABLE 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); 字符串文件名= getFileName(yourfileuri);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM