亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

startactivityforresult與權限請求的結合

小樊
85
2024-09-02 19:53:39
欄目: 編程語言

startActivityForResult和權限請求可以結合使用,以便在啟動新活動之前檢查并請求必要的權限。以下是一個簡單的示例,說明如何實現這種結合:

  1. 首先,確保在AndroidManifest.xml文件中添加了所需的權限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
  1. 在啟動新活動之前,檢查并請求相機權限(如果尚未授權):
private static final int REQUEST_CODE_PERMISSIONS = 100;

private void launchActivityWithPermissionCheck() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSIONS);
    } else {
        launchActivity();
    }
}
  1. 定義launchActivity()方法以啟動新活動:
private void launchActivity() {
    Intent intent = new Intent(this, TargetActivity.class);
    startActivityForResult(intent, REQUEST_CODE_PERMISSIONS);
}
  1. 重寫onRequestPermissionsResult()方法以處理權限請求結果:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == REQUEST_CODE_PERMISSIONS) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted, you can launch the activity now
            launchActivity();
        } else {
            // Permission denied, inform the user
            Toast.makeText(this, "Camera permission is required to launch the target activity", Toast.LENGTH_SHORT).show();
        }
    }
}
  1. TargetActivity中處理結果,并將結果返回給啟動它的活動:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_CODE_PERMISSIONS && resultCode == RESULT_OK) {
        // Permission granted, you can process the result now
        // ...
    } else {
        // Permission denied or activity finished, inform the caller activity
        setResult(RESULT_CANCELED);
        finish();
    }
}

現在,在啟動TargetActivity之前,系統會檢查并請求相機權限。如果用戶授權了權限,活動將正常啟動;否則,將顯示一條消息通知用戶需要權限。

0
库伦旗| 呼图壁县| 日土县| 兰州市| 邹城市| 千阳县| 平南县| 团风县| 锡林浩特市| 鄂托克旗| 宿松县| 吴桥县| 永和县| 富平县| 鄱阳县| 维西| 新沂市| 宜宾县| 海伦市| 商洛市| 屏东市| 台州市| 遂溪县| 张家界市| 宜昌市| 龙川县| 建湖县| 奉贤区| 兴和县| 云南省| 沅江市| 乐安县| 淮滨县| 河间市| 册亨县| 抚远县| 文安县| 烟台市| 威信县| 开鲁县| 敦化市|