中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
万盛区| 寻乌县| 阳曲县| 怀柔区| 秦安县| 荆门市| 虎林市| 简阳市| 砀山县| 巫山县| 汪清县| 泸定县| 库车县| 鸡西市| 芜湖县| 岑溪市| 鹤山市| 开远市| 边坝县| 察隅县| 遵义县| 通渭县| 华坪县| 凌云县| 孝感市| 固镇县| 拜城县| 临湘市| 汶上县| 涿鹿县| 共和县| 蓝山县| 大港区| 那坡县| 于田县| 项城市| 新源县| 涪陵区| 都兰县| 通榆县| 蓬安县|