微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法在Android上使用SMS用户同意API发送短信验证码

如何解决无法在Android上使用SMS用户同意API发送短信验证码

我正在尝试使用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);
    }

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

解决方法

调用此 API 不会向您发送短信。此 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 的电话号码是发件人的电话号码。因此,如果您知道哪个号码会向您发送短信,则将其传递给此函数。但如果您不知道发件人的号码,请将其保留为空。

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

documentation of google user Consent API

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

sending sms to android emulator

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?