问题描述
我正在尝试使用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
因此首先调用上面的创建此任务指令,让它等待您的短信,然后请求短信。您可以使用第三方平台发送短信。测试您是否可以使用模拟器向模拟器设备发送短信。