简单权限:请求Fragment的许可

时间:2016-12-14 18:34:27

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

我正在使用Easy Permissions在我的项目中实现权限模型。

我正在尝试请求权限,如下所示:

CameraFragment.java:

public class CameraFragment extends BaseFragment implements EasyPermissions.PermissionCallbacks {
    private String mCurrentPhotoPath;
    private HomeActivity mHomeActivity;

    public static CameraFragment getFragment() {
        return new CameraFragment();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == BaseConstants.REQUEST_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK) {
            galleryAddPic();
            launchActivity(AddAnotherPhotoActivity.getActivityIntent(getContext(), mCurrentPhotoPath));
        } else if (requestCode == BaseConstants.REQUEST_CODE_SETTINGS_PERMISSION_STORAGE) {
            checkStoragePermission();
        } else if (requestCode == BaseConstants.REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                mCurrentPhotoPath = FileUtils.getFile(getContext(), data.getData()).getAbsolutePath();
                launchActivity(AddAnotherPhotoActivity.getActivityIntent(mHomeActivity, mCurrentPhotoPath));
            }
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mHomeActivity = (HomeActivity) context;
    }

    @Override
    protected int getResourceLayout() {
        return R.layout.fragment_camera;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        checkStoragePermission();
    }

    private void checkStoragePermission() {
        String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(mHomeActivity, perms)) {
            // Already have permission, do the thing
            initializeSelectImage();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage),
                    BaseConstants.REQUEST_CODE_PERMISSION_STORAGE, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        // Some permissions have been granted
        // ...

        initializeSelectImage();
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        // Some permissions have been denied
        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.rationale_never_ask_storage))
                    .setTitle(getString(R.string.title_settings_dialog))
                    .setPositiveButton(getString(R.string.title_settings_button_setting))
                    .setNegativeButton(getString(R.string.title_settings_button_cancel), null /* click listener */)
                    .setRequestCode(BaseConstants.REQUEST_CODE_SETTINGS_PERMISSION_STORAGE)
                    .build()
                    .show();
        }
    }

    public void initializeSelectImage() {
        SelectImageUsingBottomSheet selectImageUsingBottomSheet = new SelectImageUsingBottomSheet();
        mHomeActivity.showDialogFragment(this, selectImageUsingBottomSheet, BaseConstants.REQUEST_CODE_SELECT_IMAGE);
    }

    public void pickImage() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        launchActivity(intent, BaseConstants.REQUEST_CODE_PICK_IMAGE, false);
    }

    public void onCameraClick() {
        captureImage();
    }

    public void onGalleryClick() {
        pickImage();
    }

    private void captureImage() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(mHomeActivity.getApplicationContext().getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File

            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(getContext(), "com.movinghub.snapyourapp.fileprovider", photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                launchActivity(takePictureIntent, BaseConstants.REQUEST_CODE_CAPTURE_IMAGE, false);
            }
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName, /* prefix */
                ".jpg",/* suffix */
                storageDir/* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        getActivity().sendBroadcast(mediaScanIntent);
    }
}

但遗憾的是,这并不奏效。不幸的是,我的应用程序因以下日志而关闭:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=65636, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.movinghub.snapyourapp/com.movinghub.snapyourapp.activity.HomeActivity}: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
                                                                           at android.app.ActivityThread.deliverResults(ActivityThread.java:3720)
                                                                           at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763)
                                                                           at android.app.ActivityThread.-wrap16(ActivityThread.java)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                           at android.os.Looper.loop(Looper.java:148)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
                                                                        Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
                                                                           at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1538)
                                                                           at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1556)
                                                                           at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:696)
                                                                           at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:662)
                                                                           at android.support.v4.app.DialogFragment.show(DialogFragment.java:143)
                                                                           at com.movinghub.snapyourapp.base.BaseAppCompatActivity.showDialogFragment(BaseAppCompatActivity.java:168)
                                                                           at com.movinghub.snapyourapp.fragment.CameraFragment.initializeSelectImage(CameraFragment.java:122)
                                                                           at com.movinghub.snapyourapp.fragment.CameraFragment.onPermissionsGranted(CameraFragment.java:101)
                                                                           at pub.devrel.easypermissions.EasyPermissions.onRequestPermissionsResult(EasyPermissions.java:301)
                                                                           at com.movinghub.snapyourapp.fragment.CameraFragment.onRequestPermissionsResult(CameraFragment.java:93)
                                                                           at android.support.v4.app.FragmentActivity.onRequestPermissionsResult(FragmentActivity.java:911)
                                                                           at com.movinghub.snapyourapp.activity.HomeActivity.onRequestPermissionsResult(HomeActivity.java:56)
                                                                           at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:6596)
                                                                           at android.app.Activity.dispatchActivityResult(Activity.java:6474)
                                                                           at android.app.ActivityThread.deliverResults(ActivityThread.java:3716)
                                                                           at android.app.ActivityThread.handleSendResult(ActivityThread.java:3763) 
                                                                           at android.app.ActivityThread.-wrap16(ActivityThread.java) 
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1403) 
                                                                           at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                           at android.os.Looper.loop(Looper.java:148) 
                                                                           at android.app.ActivityThread.main(ActivityThread.java:5443) 
                                                                           at java.lang.reflect.Method.invoke(Native Method) 
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 

任何人都可以帮我吗?

0 个答案:

没有答案