无法从系统图片选择器

时间:2016-06-27 07:25:04

标签: android image android-intent android-activity permissions

所以我实现了代码,让我使用Android中的默认图像选择器从我的文件系统中选择图像,但由于某种原因,每个图像都显示为灰色。它根本不让我选择图像。我在Marshmallow 6.0.1(从中截取屏幕截图)和Lollipop 5.1.1上进行了测试。

enter image description here

这是我的实施:

清单:

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.company.app.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

请注意,所有这些都是在同一个活动LaunchActivity.java

上完成的

使用的变量:

private ImageView picturebutton;
private Bitmap imageBitmap;
final private int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE=1;
private int PICK_IMAGE_REQUEST = 1;

ImageView充当按钮:

picturebutton = (ImageView) findViewById(R.id.chose_picture);
View.OnClickListener picturebuttonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkStorageReadPermission(LaunchActivity.this);
        }
    };
    picturebutton.setOnClickListener(picturebuttonClickListener);

请求存储访问权限的方法 checkStorageReadPermission()

public void checkStorageReadPermission(final Context context){
    if(ContextCompat.checkSelfPermission(LaunchActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
        if(ActivityCompat.shouldShowRequestPermissionRationale(LaunchActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)){
        }
        else {
            ActivityCompat.requestPermissions(LaunchActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        }
    }
    else{
        Log.d("Permissions","Permission was already granted");
        startActivity(openGallery());
    }
}

onRequestPermissionsResult()的覆盖代码:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startActivity(openGallery());
                Log.d("Permissions","Can read storage");
            } else {
                //code for deny
                Log.e("Permissions","Can't read storage");
            }
            break;
    }
}

意图 openGallery()调用图像选择器:

public Intent openGallery() {
        Intent og = new Intent();
        og.setType("image*/");
        og.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST);
        return og;
    }

调用Intent时覆盖 onActivityResult()的代码:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(resultCode,requestCode,data);
    if(requestCode==PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
        Uri imageUri = data.getData();
        try{
            imageBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);
            x.uploadImage(imageBitmap,LaunchActivity.this);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

权限请求过程没有问题,外部存储访问的系统权限对话框出现,被授予并且选择器打开,但我无法选择任何图像。帮助将不胜感激!

3 个答案:

答案 0 :(得分:0)

而不是startActivity(openGallery());,只需调用openGallery();方法即可。您已使用startActivityForResilt在该方法中启动图像选择器,因此您不需要再次startActivity()。另外,从return删除openGallery()语句。

此外,您设置的MIME类型错误。它应该是image/*。 因此,更新的应该是:

public void openGallery() {
        Intent og = new Intent();
        og.setType("image/*");
        og.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST);
    }

答案 1 :(得分:0)

OnChoose代码

        chooseimage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {



            if (Build.VERSION.SDK_INT >= 23){

                boolean result= Utility.checkPermission(getActivity());

                if(result) {
                    galleryIntent();
                }

            }

            else {
                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                // Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
                startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS
            }




        }
    });

还为“权限和设置图像”添加了代码

 public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Build.VERSION.SDK_INT >= 23) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == LOAD_IMAGE_RESULTS) {
                onSelectFromGalleryResult(data);

            }
        }
    }
    else {



                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {

                    Bitmap bitmap = null;
                    Uri selectedImage = data.getData();
                    String wholeID = DocumentsContract.getDocumentId(selectedImage);

                    // Split at colon, use second item in the array
                    String id = wholeID.split(":")[1];

                    String[] column = {MediaStore.Images.Media.DATA};

                    // where id is equal to
                    String sel = MediaStore.Images.Media._ID + "=?";

                    Cursor cursor = getActivity().getContentResolver().
                            query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                    column, sel, new String[]{id}, null);

                    String filePath = "";

                    int columnIndex = cursor.getColumnIndex(column[0]);

                    if (cursor.moveToFirst()) {
                        //filePath = cursor.getString(columnIndex);
                        mPath = cursor.getString(columnIndex);
                    }


                    cursor.close();

                }
                else {
                    if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) {
                        // Let's read picked image data - its URI
                        Uri pickedImage = data.getData();
                        // Let's read picked image path using content resolver
                        String[] filePath = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null);
                        cursor.moveToFirst();
                        mPath = cursor.getString(cursor.getColumnIndex(filePath[0]));
                        //edAttach.setText(mPath.toString()); path set anywhere
                        cursor.close();
                    }

                }
    }
}




private void onSelectFromGalleryResult(Intent data) {

    Bitmap bm=null;
    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
ivprofile.setImageBitmap(bm);
    }



    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
        Uri selectedImage = data.getData();
        String wholeID = DocumentsContract.getDocumentId(selectedImage);

        // Split at colon, use second item in the array
        String id = wholeID.split(":")[1];

        String[] column = {MediaStore.Images.Media.DATA};

        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = getActivity().getContentResolver().
                query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        column, sel, new String[]{id}, null);

        String filePath = "";

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            //filePath = cursor.getString(columnIndex);
            mPath = cursor.getString(columnIndex);
            //edAttach.setText(mPath); path set anywhere


        }
        cursor.close();
    }
    else {
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        mPath = cursor.getString(columnIndex).toString();
        System.out.println("picturePath" + mPath);
        if (!mPath.equalsIgnoreCase(null)) {
            edAttach.setText(mPath);
        }
        cursor.close();
    }

}

public boolean hasPermissionInManifest(Context context, String permissionName) {
    final String packageName = context.getPackageName();
    try {
        final PackageInfo packageInfo = context.getPackageManager()
                .getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
        final String[] declaredPermisisons = packageInfo.requestedPermissions;
        if (declaredPermisisons != null && declaredPermisisons.length > 0) {
            for (String p : declaredPermisisons) {
                if (p.equals(permissionName)) {
                    return true;
                }
            }
        }
    } catch (PackageManager.NameNotFoundException e) {

    }
    return false;
}


 public static boolean isMediaDocument(Uri uri)
{
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

private void galleryIntent()
{
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);//
    startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                galleryIntent();

            } else {
                //code for deny
            }
            break;
    }
}

或权限在mainfiest.xml中

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

<强> Utility.java

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

public class Utility {
    public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public static boolean checkPermission(final Context context)
    {
        int currentAPIVersion = Build.VERSION.SDK_INT;
        if(currentAPIVersion>= Build.VERSION_CODES.M)
        {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                    alertBuilder.setCancelable(true);
                    alertBuilder.setTitle("Permission necessary");
                    alertBuilder.setMessage("External storage permission is necessary");
                    alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                        }
                    });
                    AlertDialog alert = alertBuilder.create();
                    alert.show();
                } else {
                    ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
}

答案 2 :(得分:0)

如果您无法从列表中选择一张图片,我认为问题出在意向上。

  

调用图像选择器的意图openGallery():

public Intent openGallery() {
        Intent og = new Intent();
        og.setType("image*/");
        og.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(og,"Pick a picture"),PICK_IMAGE_REQUEST);
        return og;
    }

实际上我看到您在这里犯了一个错误

  

og.setType("image*/");

例如,您应该编写(“ image / *”)或指定扩展名(例如“” image / jpg“)!

实际上,您不需要执行

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

因为ACTION_GET_CONTENT仅选择Uri不需要此权限的图像