onRequestPermissionsResult 在 Android Fragment 中已弃用

Unk*_*scl 3 java gps android location

这是我当前(已弃用)的方法:

int LOCATION_REQUEST_CODE = 10001;     
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == LOCATION_REQUEST_CODE) {
            //Permission granted
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                checkSettingsAndStartLocationUpdates();
            } else {
                //DO SOMETHING - Permission not granted
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

根据android文档https://developer.android.com/training/basics/intents/result我应该使用registerForActivityResult():

// GetContent creates an ActivityResultLauncher<String> to allow you to pass
// in the mime type you'd like to allow the user to select
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            // Handle the returned Uri
        }
});
Run Code Online (Sandbox Code Playgroud)

然而,我正在努力更换我的方法。在新方法“registerForActivityResult()”中,我应该在哪里插入我的请求代码和 int 数组?为什么我需要一个“Uri”?

小智 6

在新方法“registerForActivityResult()”中,我应该在哪里插入我的请求代码和 int 数组?

你没有任何requestCode. requestCode在此设计中,您可以为之前使用过的每个回调考虑一个回调。为了处理单一权限,您可以使用内置的ActivityResultContracts.RequestPermission

// Register the permissions callback, which handles the user's response to the
// system permissions dialog. Save the return value, an instance of
// ActivityResultLauncher, as an instance variable.
private ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(new RequestPermission(), isGranted -> {
    if (isGranted) {
        // Permission is granted. Continue the action or workflow in your
        // app.
    } else {
        // Explain to the user that the feature is unavailable because the
        // features requires a permission that the user has denied. At the
        // same time, respect the user's decision. Don't link to system
        // settings in an effort to convince the user to change their
        // decision.
    }
});
Run Code Online (Sandbox Code Playgroud)

为什么我需要一个“Uri”?

你可能会弄错。这样,您需要一个 ActivityResultContract<Input, Output> 连接两个 Activity。以前您只能将 Intent 传递给启动的 Activity。现在您可以使用此合约传递任何类型的对象。输入是要传递的对象类型,输出是从新活动返回的结果对象的类型。有一些内置合约可以处理常规场景,其中之一是GetContent(). 如果您想要startActivityForResult(intent)类似的东西,只需使用ActivityResultContracts.StartActivityForResult,注册它将返回一个 ActivityResultLauncher,在该意图中,您可以使用该意图传递数组。

// Similar to how you pass your array with intnt before
Intent i = new Intent(MainActivity.this, NewActivity.class);
i.putExtra ("key_arr", arr); // arr is your int array
resultLauncher.launch(i);
Run Code Online (Sandbox Code Playgroud)