1

我正在尝试使用 java 在 android studio 上进行电话号码验证。我按照此处文档中的说明进行操作https://developers.google.com/identity/sms-retriever/user-consent/overview但遗憾的是它没有向我发送 SMS 代码,我也没有收到任何错误。下面是我的代码:

public class OTPSMSActivity extends AppCompatActivity {
    private ImageView blur;
    private TextView resend;
    private CustomEditText editText;
    private FirebaseFirestore db = FirebaseFirestore.getInstance();
    private KProgressHUD loadingBar;
    private static final int SMS_CONSENT_REQUEST = 2;

    // Set to an unused request code
    private final BroadcastReceiver smsVerificationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
                Bundle extras = intent.getExtras();
                Status smsRetrieverStatus = (Status) extras.get(SmsRetriever.EXTRA_STATUS);

                switch (smsRetrieverStatus.getStatusCode()) {
                    case CommonStatusCodes.SUCCESS:
                        // Get consent intent
                        Intent consentIntent = extras.getParcelable(SmsRetriever.EXTRA_CONSENT_INTENT);
                        try {
                            /*Start activity to show consent dialog to user within
                             *5 minutes, otherwise you'll receive another TIMEOUT intent
                             */
                            startActivityForResult(consentIntent, SMS_CONSENT_REQUEST);
                            Log.d("life", "Intent to send image");
                        } catch (ActivityNotFoundException e) {
                            Log.e("life", "Exception: " + e.toString());
                        }
                        break;
                    case CommonStatusCodes.TIMEOUT:
                        Log.d("life", "Timeout!");
                        break;
                }
            } else {
                Log.d("life", "SmsRetriever don't matched");
            }
        }
    };


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

        blur = findViewById(R.id.blur);
        editText = findViewById(R.id.number);
        Button verify = findViewById(R.id.verify);
        TextView change = findViewById(R.id.textView42);
        resend = findViewById(R.id.resend);

        Paper.init(this);

        getBackgroundImage();

        change.setOnClickListener(view -> {
            finish();
        });


        String phoneNumber = getIntent().getStringExtra("phone");

        loadingBar = KProgressHUD.create(OTPSMSActivity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setLabel("Please wait")
                .setDetailsLabel("Sending sms code to your phone number.")
                .setCancellable(true)
                .setAnimationSpeed(2)
                .setDimAmount(0.5f)
                .show();

        verify.setOnClickListener(view -> {
            loadingBar = KProgressHUD.create(OTPSMSActivity.this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setLabel("Loading")
                    .setDetailsLabel("Verifying code")
                    .setCancellable(true)
                    .setAnimationSpeed(2)
                    .setDimAmount(0.5f)
                    .show();
            String theCode = editText.getText().toString();
            if (theCode.length() != 6){
                new StyleableToast
                        .Builder(OTPSMSActivity.this)
                        .text("Invalid code.")
                        .iconStart(R.drawable.error)
                        .textColor(Color.WHITE)
                        .backgroundColor(getResources().getColor(R.color.error))
                        .show();
                editText.setError("Invalid phone number.");
                editText.requestFocus();
                loadingBar.dismiss();
                return;
            }
            verifyCode(theCode);
        });

        resend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        String phone = "+63" + phoneNumber.substring(1);
        Log.d("life", phone);
        Task<Void> task = SmsRetriever.getClient(this).startSmsUserConsent(phone);

        task.addOnCompleteListener(listener -> {
            if (listener.isSuccessful()) {
                Log.d("life", "Success");
                loadingBar.dismiss();

                IntentFilter intentFilter = new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION);
                registerReceiver(smsVerificationReceiver, intentFilter);
            } else {
                Exception exception = listener.getException();
                exception.printStackTrace();
            }
        });
    }

    private void verifyCode(String code) {
        if (code.equals(editText.getText().toString())) {
            String phoneNumber = getIntent().getStringExtra("phone");
            String userID = Paper.book().read("userID");

            loadingBar.setDetailsLabel("Uploading number to database");
            db.collection("Buyers").document(userID)
                    .update("phone", "+63" + phoneNumber.substring(1))
                    .addOnCompleteListener(task11 -> {
                        if (task11.isSuccessful()){
                            loadingBar.dismiss();
                            StyleableToast.makeText(OTPSMSActivity.this, "Success! Phone number updated.", Toast.LENGTH_LONG, R.style.successtoast).show();
                            finish();
                        }
                    });
        } else {
            new StyleableToast
                    .Builder(OTPSMSActivity.this)
                    .text("Code does not matched.")
                    .iconStart(R.drawable.error)
                    .textColor(Color.WHITE)
                    .backgroundColor(getResources().getColor(R.color.error))
                    .show();
            loadingBar.dismiss();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SMS_CONSENT_REQUEST) {
            if (resultCode == RESULT_OK) {
                // Get SMS message content
                String message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE);
                // Extract one-time code from the message and complete verification
                String oneTimeCode = parseOneTimeCode(message);
                Log.d("life", "oneTimeCode: " + oneTimeCode);
                //for this demo we will display it instead
                editText.setText(oneTimeCode);
            } else {
                Log.d("life", "Error2");
            }
        } else {
            Log.d("life", "Error1");
        }
    }


    private String parseOneTimeCode(String message) {
        //simple number extractor
        return message.replaceAll("[^0-9]", "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //to prevent IntentReceiver leakage unregister
        unregisterReceiver(smsVerificationReceiver);
    }

我想知道我在这里做错了什么。

4

1 回答 1

1

调用此 API 不会向您发送 SMS。此 API 侦听您将在您的设备上收到的 SMS,请求您的许可,然后检索它。

您不应等待任务完成。它可以收听您收到的短信。因此,您需要在 onCreate 函数中更正的第一件事是:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otpsms);
        ...
        
        Task<Void> task = SmsRetriever.getClient(this).startSmsUserConsent(null);

        IntentFilter intentFilter = new IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION);
        registerReceiver(smsVerificationReceiver, intentFilter);

        ...
   }

您传递给SmsRetriever.getClient(this).startSmsUserConsent的电话号码是发件人的电话号码。因此,如果您知道哪个号码会向您发送 SMS,则将其传递给此函数。但是,如果您不知道发件人的号码,请将其保留为空。

请注意,发件人电话号码不应出现在文档中提到的手机联系人列表中:https ://developers.google.com/identity/sms-retriever/choose-an-api

谷歌用户同意 API 的文档

所以首先调用上面的创建这个任务指令,让它等待你的短信,然后请求短信。您可以使用第三方平台发送短信。要测试您可以使用模拟器向模拟器设备发送短信。

发送短信到安卓模拟器

于 2021-03-02T17:04:10.213 回答