【问题标题】:onactivityresult() is deprecated in android fragmentonactivityresult() 在 android 片段中已弃用
【发布时间】:2021-07-06 10:08:31
【问题描述】:

我在 google 上搜索 onactivityresult() 已弃用。但我的问题没有解决。这是片段的代码

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {

        switch (requestCode){
            case CAMERA_REQUEST_CODE:{
                if (grantResults.length >0 ){
                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean writeStorageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    if (cameraAccepted && writeStorageAccepted){
                        pickFromCamera();
                    }
                    else {
                        Toast.makeText(getActivity(), "Please enable camera & storage permission first ", Toast.LENGTH_SHORT).show();
                    }

                }

            }
   private void pickFromCamera() {

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE,"Temp Pic");
        values.put(MediaStore.Images.Media.DESCRIPTION,"Temp Description");
        // put image uri
        image_uri = requireActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        // intent tom start camera
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
        startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);

    }

    private void pickFromGallery() {
        // pick from gallery
        Intent galleryIntent = new Intent(Intent .ACTION_PICK);
        galleryIntent.setType("Images/*");
        startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
    }

}

【问题讨论】:

标签: java android deprecated


【解决方案1】:

Kotlin - 下面的代码而不是 startActivityForResult 弃用 此方法本身给出结果并返回一个值。

val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    when (result.resultCode) {
        Activity.RESULT_OK -> {
            // logic
        }
        else -> {
            // logic
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 2019-01-23
    • 2022-10-02
    • 1970-01-01
    • 2014-07-25
    • 2014-03-30
    • 2013-12-02
    • 1970-01-01
    相关资源
    最近更新 更多