You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用KeyguardManager按钮触发锁屏验证跳转页面异常求助

问题修复:Android设备锁屏验证后跳转页面异常

问题1:点击按钮直接跳转,锁屏验证不触发

你的authScreen方法里,无论锁屏验证逻辑是否执行,最后都会无条件执行跳转代码,导致验证弹窗还没启动就直接跳去了SearchActivity。必须把跳转逻辑放到验证成功后的回调里,而非方法末尾。

问题2:ActivityResultLauncher回调不触发

代码里的startActivityForResult.launch(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS)存在两处错误:

  • 变量名写错:应该用你注册的activityResultLaunch,而非startActivityForResult
  • 新版ActivityResultLauncher的launch方法不需要传请求码,这是旧版startActivityForResult的用法,新版仅需传入Intent

修改后的完整代码

// 注册ActivityResultLauncher
ActivityResultLauncher<Intent> activityResultLaunch = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // 验证成功,跳转目标页面
                    Intent intent = new Intent(DetectorActivity.this, SearchActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // 验证失败,关闭当前页面或提示用户
                    finish();
                }
            }
        });

start_end_button_add.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        authScreen(activityResultLaunch);
    }
});

private void authScreen(ActivityResultLauncher<Intent> activityResultLaunch) {
    KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    if (!mKeyguardManager.isKeyguardSecure()) {
        // 提示用户未设置锁屏密码
        Toast.makeText(this, "请先设置设备锁屏密码", Toast.LENGTH_SHORT).show();
    } else {
        Intent intent = mKeyguardManager.createConfirmDeviceCredentialIntent("验证管理员身份", "请输入设备密码以访问敏感页面");
        
        if (intent != null) {
            // 正确调用launch方法,仅传入Intent
            activityResultLaunch.launch(intent);
        } else {
            Toast.makeText(this, "无法启动锁屏验证", Toast.LENGTH_SHORT).show();
        }
    }
    // 移除原有的直接跳转代码,逻辑移至回调中
}

关键修改说明

  • 将跳转SearchActivity的代码移到onActivityResult的RESULT_OK分支,确保只有验证成功才会跳转
  • 修正ActivityResultLauncher的调用方式,去掉错误的请求码参数,使用正确的变量名
  • 给锁屏验证Intent添加了标题和提示文本,优化用户体验
  • 补充了未设置锁屏、无法启动验证的提示逻辑

内容的提问来源于stack exchange,提问作者Hilmi Marzuqi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:39:28