授予必要的权限后,EACCES(权限被拒绝)

时间:2016-06-02 06:51:18

标签: android permissions

好吧所以我在模拟器上测试我的应用程序时遇到此问题(android 6.0)(因为我没有安装android 6.0设备),我首先要求用户在执行任务之前授予必要的权限,并在获得权限之后执行我的任务,但它给了我这个错误:

Unable to decode stream: java.io.FileNotFoundException: /storage/19FA-1F0B/DCIM/Image1464800718267.jpg: open failed: EACCES (Permission denied)
06-02 12:04:11.906 21595-21595/pb.myPackage D/AndroidRuntime: Shutting down VM                                                                

                                                                ----------beginning of crash
06-02 12:04:11.907 21595-21595/pb.myPackage E/AndroidRuntime: FATAL EXCEPTION: main
                                                                Process: pb.myPackage, PID: 21595
                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{pb.myPackage/pb.myPackage.CropActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap$Config android.graphics.Bitmap.getConfig()' on a null object reference
                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                    at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                    at android.os.Looper.loop(Looper.java:148)
                                                                    at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap$Config android.graphics.Bitmap.getConfig()' on a null object reference

我的整个代码在哪里询问然后执行我的任务:

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

                if (ContextCompat.checkSelfPermission(context,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {

                    requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_CODE_ASK_PERMISSIONS);

                }else {


                    //Start Activity To Select Image From Gallery
                    Intent gallery_Intent = new Intent(getContext(), GalleryUtil.class);
                    gallery_Intent.putExtra("Switch", 0);
                    startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
                }


            }else {



                //Start Activity To Select Image From Gallery
                Intent gallery_Intent = new Intent(getContext(), GalleryUtil.class);
                gallery_Intent.putExtra("Switch", 0);
                startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);

            }

你可以看到我正在检查是否授予了必要的权限,但仍然得到了这个例外,最重要的一点是,这只发生在我第一次执行上述所有任务时,首先是用户授予我获得此错误的权限,但当我再次运行应用程序时,我没有得到任何例外,一切正常,

似乎当用户授予权限时,此新更改尚未在系统上更新,并且在重新启动后更改更新完成并且一切正常

onActivityResult:

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GALLERY_ACTIVITY_CODE) {
        if(resultCode == Activity.RESULT_OK) {

            String picturePath = data.getStringExtra("picturePath");


            //perform Crop on the Image Selected from Gallery
            performCrop(picturePath);}}

    if (requestCode == RESULT_CROP ) {
        if(resultCode == Activity.RESULT_OK){
            Bundle extras = data.getExtras();
            Bitmap selectedBitmap = extras.getParcelable("data");
            // Set The Bitmap Data To ImageView
            imageView.setImageBitmap(selectedBitmap);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);}}
}


private void performCrop(String imageUri) {

    Intent cropIntent = new Intent(getActivity(), CropActivity.class );
    cropIntent.putExtra("imageUri", imageUri);
    startActivity(cropIntent);
    getActivity().finish();
}

在获取图像后发送它进行裁剪,然后从那里得到图像,错误发生在CropActivity.class

galleryClass:

public class GalleryUtil extends Activity{
private final static int RESULT_SELECT_IMAGE = 100;
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "GalleryUtil";

String mCurrentPhotoPath;
File photoFile = null;
Intent selectedImageIntent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try{
        //Pick Image From Gallery
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, RESULT_SELECT_IMAGE);
    }catch(Exception e){
        e.printStackTrace();
    }
}

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

    switch(requestCode){
        case RESULT_SELECT_IMAGE:

            if (resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
                try{


                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();

                    //return Image Path to the Main Activity
                    Intent returnFromGalleryIntent = new Intent();
                    returnFromGalleryIntent.putExtra("Switch", false);
                    returnFromGalleryIntent.putExtra("picturePath",picturePath);
                    setResult(RESULT_OK,returnFromGalleryIntent);
                    finish();



                }catch(Exception e){
                    e.printStackTrace();
                    Intent returnFromGalleryIntent = new Intent();
                    setResult(RESULT_CANCELED, returnFromGalleryIntent);
                    finish();
                }
            }else{
                Log.i(TAG, "RESULT_CANCELED");
                Intent returnFromGalleryIntent = new Intent();
                setResult(RESULT_CANCELED, returnFromGalleryIntent);
                finish();
            }
            break;
    }
}

cropActivity:

    public class CropActivity extends Activity {


    File savedFile;
    Button btnCancel;
    Context context;
    PhotoViewAttacher mAttacher;


    Bitmap mImage;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.new_crop_actvity);


            final CropImageView cropImageView = (CropImageView)findViewById(R.id.cropImageView);
            final ImageView croppedImageView = (ImageView)findViewById(R.id.croppedImageView);
            final  ImageView  bgImgView = (ImageView) findViewById(R.id.blurBGImgView);

            btnCancel = (Button)findViewById(R.id.btnCancel);

            context = this.getBaseContext();






            mAttacher = new PhotoViewAttacher(croppedImageView);

            Uri imgUri1 = Uri.parse(getIntent().getExtras().getString("imageUri"));

            String UriStr = imgUri1.toString();


            File f = new File(UriStr);
            final String filePath = f.getPath();
            Bitmap bitmap = BitmapFactory.decodeFile(filePath);
            cropImageView.setImageBitmap(bitmap);


            Bitmap blurredBitmap = Blur.fastblur(this, bitmap, 20);

            bgImgView.setImageBitmap(blurredBitmap);


            cropImageView.setCropMode(CropImageView.CropMode.CIRCLE);



            //customising crop activity
            cropImageView.setBackgroundColor(getResources().getColor(R.color.transparent));
            cropImageView.setOverlayColor(0xAA1C1C1C);
            cropImageView.setFrameColor(getResources().getColor(R.color.transparent));
            cropImageView.setHandleColor(getResources().getColor(R.color.transparent));
            cropImageView.setGuideColor(getResources().getColor(R.color.transparent));


            // Set image for cropping
            //cropImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));

            //cropImageView.setImageBitmap(mImage);


            Button cropButton = (Button)findViewById(R.id.crop_button);
            cropButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //  Bitmap CroppedIamge = cropImageView.getCroppedBitmap();
                    // Get cropped image, and show result.
                    croppedImageView.setImageBitmap(cropImageView.getCroppedBitmap());



                    View content = croppedImageView;
                    content.setDrawingCacheEnabled(true);
                    Bitmap bitmap = content.getDrawingCache();

//
//                    File root = Environment.getExternalStorageDirectory();
//                    File file = new File(root.getAbsolutePath() + "/Download/img.jpg");


                  //  File root = Environment.getExternalStorageDirectory();
                    File file = new File(context.getApplicationContext().getFilesDir() + "/img.gpj");



                    String path = file.getPath();
//                    File file = new File("/DCIM/Camera/image.jpg");
                    try {
                        file.createNewFile();
                        FileOutputStream ostream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, ostream);


                        savedFile = new File(path);


                        ostream.close();
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();

                    }


                    croppedImageView.buildDrawingCache();
                    Bitmap CroppedIamge = croppedImageView.getDrawingCache();


                   Intent sendCroppedImgIntent = new Intent(CropActivity.this, MainActivity.class);
                    Bundle extras = new Bundle();
                    //extras.putParcelable("imagebitmap", CroppedIamge);
                    extras.putString("croppedImgUri", savedFile.toString() );
                    extras.putInt("Switch",1);
                    sendCroppedImgIntent.putExtras(extras);
                    startActivity(sendCroppedImgIntent);




                }
            });
        }


    public void cancel(View view) {

        Intent cancelIntent = new Intent(CropActivity.this, MainActivity.class);
        startActivity(cancelIntent);

    }
}

1 个答案:

答案 0 :(得分:0)

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

            if (ContextCompat.checkSelfPermission(ActivityName.this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_CODE_ASK_PERMISSIONS);

            } else {

                Intent gallery_Intent = new Intent(getContext(), GalleryUtil.class);
                gallery_Intent.putExtra("Switch", 0);
                startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
            }
        } else {
            //Start Activity To Select Image From Gallery
            Intent gallery_Intent = new Intent(getContext(), GalleryUtil.class);
            gallery_Intent.putExtra("Switch", 0);
            startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
        }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                final int numOfRequest = grantResults.length;
                final boolean isGranted = numOfRequest == 1
                        && PackageManager.PERMISSION_GRANTED == grantResults[numOfRequest - 1];
                if (isGranted) {
                    Intent gallery_Intent = new Intent(getContext(), GalleryUtil.class);
                    gallery_Intent.putExtra("Switch", 0);
                    startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }