我想在不使用第三方的情况下进行手机号码验证。为此,我的逻辑是:-
这个逻辑对还是需要修改?
要发送短信,我正在使用此代码,但不知道如何接收和验证号码。
String phoneNumber = "9999999999";
String smsBody = "Message from the API";
// Get the default instance of SmsManager
SmsManager smsManager = SmsManager.getDefault();
// Send a text based SMS
smsManager.sendTextMessage(phoneNumber, null, smsBody, null, null);
更新:-
未在三星设备上接收消息。
最佳答案
首先,我生成一个 10000 到 99999 范围内的随机数。
Random rNo = new Random();
final int code = rNo.nextInt((99999 - 10000) + 1) + 10000;
接下来,我会显示一个弹出窗口,提示用户将从手机发送一条消息来验证号码。这是使用 AlertDialog 完成的。
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Verify Phone Number");
builder.setMessage("An sms will be sent to the number " + phNo + " for verification. Charges will apply as per your plan");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, int which) {
//code to send sms here with the code value
final ProgressDialog progressdialog = ProgressDialog.show(getActivity(), "Waiting for SMS", "Please hold on");
final CountDownTimer timer = new CountDownTimer(120000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.v("ranjapp", "Ticking " + millisUntilFinished / 1000);
progressdialog.setMessage("Waiting for the message " + millisUntilFinished / 1000);
}
@Override
public void onFinish() {
getActivity().unregisterReceiver(receiver);
progressdialog.dismiss();
}
}.start();
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
if (readSMS(intent, code)) {
Log.v("ranjapp", "SMS read");
timer.cancel();
try {
getActivity().unregisterReceiver(receiver);
} catch (Exception e) {
}
}
}
}
};
getActivity().registerReceiver(receiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
}
);
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
builder.show();
上面代码的解释:
在用户确认发送短信后,一 strip 有代码的短信会发送到输入的号码,这个号码应该是用户自己使用的号码。因此,我们将等待带有代码的短信,接收短信并读取其内容,我们将创建一个 BroadCastReceiver 来收听传入的短信。
现在我们还需要启动一个计时器,这样我们只等待 2 分钟的短信,所以我们启动一个 CountDownTimer 2 分钟,在 2 分钟结束时,倒计时计时器将注销接收器.即使在传入的短信中收到代码,接收者也未注册,以便我们可以释放资源。
读取短信的代码,如果找到则返回true,否则返回false,
boolean readSMS(Intent intent, int code) {
try {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
if (message.contains(String.valueOf(code)))
return true;
}
}
} catch (Exception e) {
Log.v("ranjapp", "Exception here " + e.toString());
return false;
}
return false;
}
要发送短信,请使用以下方法:
public static void sendSMS(Context context, String incomingNumber, String sms) {
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("YYYY-MM-dd HH:MM:SS");
SmsManager smsManager = SmsManager.getDefault(); //send sms
try {
ArrayList<String> parts = smsManager.divideMessage(sms);
smsManager.sendMultipartTextMessage(incomingNumber, null, parts, null, null);
RecContDBHelper recContDBHelper = new RecContDBHelper(context);
recContDBHelper.insertRecord(new ContactData("", incomingNumber, dtfOut.print(MutableDateTime.now())));
Log.v("ranjith", "Sms to be sent is " + sms);
} catch (Exception e) {
Log.v("ranjith", e + "");
}
}
在 AndroidManifest.xml 中你需要有这些权限:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
关于java - 发送和接收短信以验证手机号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190446/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在处理旧代码的一部分。beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)endRubocop错误如下:Avoidstubbingusing'allow_any_instance_of'我读到了RuboCop::RSpec:AnyInstance我试着像下面那样改变它。由此beforedoallow_any_instance_of(SportRateManager).toreceive(:create).and_return(true)end对此:let(:sport_