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

如何取消Firebase中正在进行的手机号认证请求?

如何取消Firebase PhoneAuth的验证码请求(Java实现)

Firebase PhoneAuth SDK目前没有提供直接取消verifyPhoneNumber请求的官方API,以下是几个简洁的替代方案,避免复杂的状态保存逻辑:

方案1:通过Activity生命周期标记请求状态

在「发送验证码」Activity销毁时,标记请求为已取消,后续回调触发时直接跳过业务处理,从应用层面忽略未完成请求的影响。

public class VerifyPhoneActivity extends AppCompatActivity {
    private boolean isRequestCancelled = false;
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_phone);

        // 初始化回调,添加取消判断
        mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onVerificationCompleted(PhoneAuthCredential credential) {
                if (isRequestCancelled) return;
                // 正常处理认证完成逻辑
            }

            @Override
            public void onVerificationFailed(FirebaseException e) {
                if (isRequestCancelled) return;
                // 处理认证失败逻辑
            }

            @Override
            public void onCodeSent(String verificationId, PhoneAuthProvider.ForceResendingToken token) {
                if (isRequestCancelled) return;
                // 保存verificationId和token用于后续验证
            }
        };

        // 发送验证码按钮点击事件
        findViewById(R.id.btn_send_code).setOnClickListener(v -> {
            String phoneNumber = "你的手机号";
            PhoneAuthOptions options = PhoneAuthOptions.newBuilder(FirebaseAuth.getInstance())
                    .setPhoneNumber(phoneNumber)
                    .setTimeout(60L, TimeUnit.SECONDS)
                    .setActivity(this)
                    .setCallbacks(mCallbacks)
                    .build();
            PhoneAuthProvider.verifyPhoneNumber(options);
        });

        // 返回主Activity按钮
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 标记请求已取消
        isRequestCancelled = true;
    }
}

方案2:结合ViewModel控制请求状态(MVVM架构适用)

如果项目采用MVVM架构,可以通过ViewModel中的LiveData传递取消状态,让回调逻辑根据状态决定是否执行:

ViewModel代码

public class VerifyPhoneViewModel extends ViewModel {
    private final MutableLiveData<Boolean> isRequestCancelled = new MutableLiveData<>(false);

    public void markRequestCancelled() {
        isRequestCancelled.setValue(true);
    }

    public LiveData<Boolean> getIsRequestCancelled() {
        return isRequestCancelled;
    }
}

Activity代码

public class VerifyPhoneActivity extends AppCompatActivity {
    private VerifyPhoneViewModel viewModel;
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_phone);

        viewModel = new ViewModelProvider(this).get(VerifyPhoneViewModel.class);

        mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
            @Override
            public void onVerificationCompleted(PhoneAuthCredential credential) {
                if (viewModel.getIsRequestCancelled().getValue() == Boolean.TRUE) return;
                // 处理认证完成逻辑
            }

            // 其他回调方法同理添加判断
        };

        // 订阅取消状态,可同步更新UI(比如重置倒计时按钮)
        viewModel.getIsRequestCancelled().observe(this, cancelled -> {
            if (cancelled) {
                findViewById(R.id.btn_send_code).setEnabled(true);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewModel.markRequestCancelled();
    }
}

方案3:重置UI状态允许重新发起请求

当用户返回主Activity再回到「发送验证码」页面时,直接重置发送按钮状态(比如重新启用按钮),结合方案1的取消标记,即使旧请求仍在超时中,新请求的错误提示(Firebase会拒绝重复请求)可以友好处理,同时旧请求的回调不会干扰当前页面逻辑。

补充说明

目前Firebase官方尚未提供取消验证码请求的API,上述方案都是从应用层面对请求的后续影响进行控制,是比onSaveInstanceState更轻量的简洁方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:12:26