手机号码将在一个EditText通过用户注册页面在我的Android应用程序中输入。 我如何检查用户输入他/她的手机号码,而不是其他的?
我已经试过这样:
TelephonyManager tMgr =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = tMgr.getLine1Number();
而这个变量与EditText上的文字进行比较。 但mPhoneNumber在我的情况下返回NULL。 是否有任何其他的选择吗? 如何解决这个问题?
任何帮助将是明显的。
我曾经尝试这样做:检查源代码:
public class MainActivity extends Activity{
Button submit;
EditText contact;
String phNo;
ProgressDialog progress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contact = (EditText)findViewById(R.id.mobileNumber);
submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
phNo = contact.getText().toString();
new CheckOwnMobileNumber().execute();
Toast.makeText(getApplicationContext(), phNo, Toast.LENGTH_LONG).show();
}
});
}
private class CheckOwnMobileNumber extends AsyncTask<String, Void, String>
{
@Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
if(progress.isShowing())
{
progress.dismiss();
// Check SMS Received or not after that open dialog date
/*if(SMSReceiver.str.equals(phNo))
{
Toast.makeText(getApplicationContext(), "Thanks for providing your number.", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Provide your own mobile number please.", Toast.LENGTH_LONG).show();
return;
}*/
}
}
@Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
String msg = phNo;
try
{
sendSMS(phNo, msg);
}
catch(Exception ex)
{
Log.v("Exception :", ""+ex);
}
return null;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress = ProgressDialog.show(MainActivity.this, "","Checking Mobile Number...");
progress.setIndeterminate(true);
progress.getWindow().setLayout(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
super.onPreExecute();
}
}
private void sendSMS(String phoneNumber, String message)
{
//PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
}
接收器收听收到或不短信?
public class SMSReceiver extends BroadcastReceiver
{
private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
Context mContext;
private Intent mIntent;
static String address, str = null;
// Retrieve SMS
public void onReceive(Context context, Intent intent) {
mContext = context;
mIntent = intent;
String action = intent.getAction();
if(action.equals(ACTION_SMS_RECEIVED))
{
SmsMessage[] msgs = getMessagesFromIntent(mIntent);
if (msgs != null)
{
for (int i = 0; i < msgs.length; i++)
{
address = msgs[i].getOriginatingAddress();
str = msgs[i].getMessageBody().toString();
}
}
// ---send a broadcast intent to update the SMS received in the
// activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
public static SmsMessage[] getMessagesFromIntent(Intent intent)
{
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0; i < messages.length; i++)
{
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i < pduCount; i++)
{
pdus[i] = pduObjs[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]);
}
return msgs;
}
}
logcat的:
03-13 17:31:02.049: E/ActivityManager(161): ANR in com.example.test
03-13 17:31:02.049: E/ActivityManager(161): Reason: Broadcast of Intent { act=android.provider.Telephony.SMS_RECEIVED cmp=com.example.test/.SMSReceiver (has extras) }
03-13 17:31:02.049: E/ActivityManager(161): 54% 3732/com.example.test: 54% user + 0% kernel / faults: 21 minor
03-13 17:31:02.049: E/ActivityManager(161): 40% 3732/com.example.test: 40% user + 0% kernel / faults: 2 minor
03-13 17:31:30.699: I/ActivityManager(161): Killing com.example.test (pid=3732): user's request
03-13 17:31:30.799: I/ActivityManager(161): Process com.example.test (pid 3732) has died.
03-13 17:31:30.799: I/WindowManager(161): WIN DEATH: Window{40992f50 com.example.test/com.example.test.MainActivity paused=false}
03-13 17:31:30.819: E/InputDispatcher(161): channel '40818670 com.example.test/com.example.test.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x8
03-13 17:31:30.819: E/InputDispatcher(161): channel '40818670 com.example.test/com.example.test.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
03-13 17:34:59.649: I/ActivityManager(161): Start proc com.example.test for broadcast com.example.test/.SMSReceiver: pid=4037 uid=10098 gids={}
Answer 1:
它不能保证tMgr.getLine1Number();
总是会返回SIM卡中的号码。 因为它依赖于一些在SIM卡的可用性。 就像在我的情况,我的TRE-瑞典SIM卡中没有我的电话号码。
但是,如果你把SIM卡插入旧的索尼爱立信,诺基亚手机,那么你会得到编辑此号码(SIM卡)的选项。 一旦其完成后,Android设备将识别号码,会告诉你。
此外,如果你通过代码得到你的电话号码,然后来比较两个数字最好的方法是:
boolean isSame = PhoneNumberUtils.compare(num1, num2);
另外,您也可以实现某种形式的PIN码验证逻辑(如Viber的,WhatsApp的或其他应用程序一样)在其中要求用户注册时输入自己的电话号码。 后来,该电话号码被发送到服务器,并针对其经由SMS发送给用户该号码生成的PIN码。 最后,用户必须输入PIN码(在SMS接收的)来完成注册。
要么
只需发送从用户的设备的SMS(带同意)到你的服务器/设备,并了解他们的电话号码。
Answer 2:
获取使用的电话号码getLine1Number()
是不安全的 ,也不一定 。
人们普遍接受,因为这整个“获得的电话号码”是多个问题作为用户的隐私,运营商的品牌,甚至供应商的这种冲突。
总之,不像IOS,Android的android.provider.Telephony.SMS_RECEIVED
使得整个过程非常方便和无缝的用户:你得到捕获短信和无需任何用户干预的阅读。
什么是这样做的一种方式?
在您的服务器在接收到验证电话号码的要求,你应该生成一个密码,tokenSent,并将其发送到应用程序。 现在,您的服务器应该通过短信到指定的手机号码发送验证码。 现在的应用程序应该有一个注册的接收器监听android.provider.Telephony.SMS_RECEIVED
意图。 一旦收到,应用程序验证tokenSent是相同的东西从服务器接收它。 此时,电话注册完成,服务器可以通知。
怎么会错呢?
一般来说,这样的应用程序通常是付费应用,它是不是用户的良好尝试任何事情。 尽管如此,用户可能输错了号码,他现在有。 然后在接收到短信,他可以将其转发到应用程序正在注册的移动。 然后该应用程序将收到tokenSent和错误验证电话号码。
我们怎样才能解决呢?
该解决方案的可行性取决于短信提供商是否允许你的服务器知道发送者的电话号码。 这可能是(据我所知)不会发生的,但如果这样做,那么你很幸运。 这样,应用程序可以在收到tokenSent,发送回服务器与手机短信的发送者一起。 然后,服务器可以验证这是起源于服务提供商的短信。
任何更可行的解决方案? (如果我真的偏执)
在这种情况下,最好的解决办法,我相信,会从服务器请求一个tokenSent。 服务器以及电话号码输入节省了产生tokenSent,并将此令牌的应用程序。 该应用程序通知注册将花费他1个SMS用户。 一旦用户接受,你可以很容易地在装有该tokenSent一定的服务后台发送短信。 服务器中,一旦接收到该验证tokenSent使用令牌和SMS的发送者用户。 当然,这可能看起来有点骚扰和侵犯用户,但它是最安全的方式,尤其是对于这样一个偏执狂(阅读本部分)。
手续:P
Add Permissions in Manifest
<uses-permission android:name="android.permission.RECEIVE_SMS">
Register the receiver
(做此发送短信到手机之前)
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getExtras() != null)
{
Object[] pdus = (Object[]) intent.getExtras().get("pdus");
SmsMessage[] msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
String from = msgs[i].getOriginatingAddress();
String body = msgs[i].getMessageBody().toString();
//here is the body
//...
unregisterReceiver(this); //If you are done with verification
}
}
}
}, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
Answer 3:
我解决了它我自己。 这是我工作的代码。 MainActivity类别:
public class MainActivity extends Activity
{
Button submit;
EditText contact;
static String phNo;
ProgressDialog progress;
static Boolean wasMyOwnNumber;
static Boolean workDone;
final static int SMS_ROUNDTRIP_TIMOUT = 30000;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contact = (EditText)findViewById(R.id.mobileNumber);
submit = (Button) findViewById(R.id.button1);
wasMyOwnNumber = false;
workDone = false;
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
phNo = contact.getText().toString();
new CheckOwnMobileNumber().execute();
}
});
}
private class CheckOwnMobileNumber extends AsyncTask<String, Void, String>
{
@Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
if(progress.isShowing())
{
progress.dismiss();
if(wasMyOwnNumber)
{
Toast.makeText(getApplicationContext(), "Number matched.", Toast.LENGTH_LONG).show();
wasMyOwnNumber = false;
workDone = false;
}
else
{
Toast.makeText(getApplicationContext(), "Wrong number.", Toast.LENGTH_LONG).show();
wasMyOwnNumber = false;
workDone = false;
return;
}
}
super.onPostExecute(result);
}
@Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
String msg = phNo;
try
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phNo, null, msg, null, null);
timeout();
}
catch(Exception ex)
{
Log.v("Exception :", ""+ex);
}
return null;
}
@Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
progress = ProgressDialog.show(MainActivity.this, "","Checking Mobile Number...");
progress.setIndeterminate(true);
progress.getWindow().setLayout(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
super.onPreExecute();
}
}
private boolean timeout()
{
int waited = 0;
while (waited < SMS_ROUNDTRIP_TIMOUT)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
waited += 100;
if(phoneNumberConfirmationReceived())
{
waited=SMS_ROUNDTRIP_TIMOUT;
workDone = true;
}
}
/*Log.v("MainActivity:timeout2: Waited: " , ""+waited);
Log.v("MainActivity:timeout2:Comparision: ", ""+ phoneNumberConfirmationReceived());
Log.v("MainActivity:timeout2: WorkDone value after wait complete : ", ""+workDone);*/
return workDone;
}
private boolean phoneNumberConfirmationReceived()
{
if(wasMyOwnNumber)
{
workDone = true;
}
return workDone;
}
}
SMSReceiver代码:
public class SMSReceiver extends BroadcastReceiver
{
private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
Context mContext;
private Intent mIntent;
static String address, str = null;
boolean isSame;
// Retrieve SMS
public void onReceive(Context context, Intent intent)
{
mContext = context;
mIntent = intent;
String action = intent.getAction();
if(action.equals(ACTION_SMS_RECEIVED))
{
SmsMessage[] msgs = getMessagesFromIntent(mIntent);
if (msgs != null)
{
for (int i = 0; i < msgs.length; i++)
{
address = msgs[i].getOriginatingAddress();
str = msgs[i].getMessageBody().toString();
}
}
Log.v("Originating Address : Sender :", ""+address);
Log.v("Message from sender :", ""+str);
isSame = PhoneNumberUtils.compare(str, MainActivity.phNo);
Log.v("Comparison :", "Yes this true. "+isSame);
if(isSame)
{
MainActivity.wasMyOwnNumber = isSame;
MainActivity.workDone=true;
}
// ---send a broadcast intent to update the SMS received in the
// activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
public static SmsMessage[] getMessagesFromIntent(Intent intent)
{
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0; i < messages.length; i++)
{
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i < pduCount; i++)
{
pdus[i] = pduObjs[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]);
}
return msgs;
}
}
没有发现ANR。
Answer 4:
public class MainActivity extends Activity{
Button submit;
EditText contact;
String phNo;
ProgressDialog progress;
Boolean wasMyOwnNumber = false;
Boolean workDone = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contact = (EditText)findViewById(R.id.mobileNumber);
submit = (Button) findViewById(R.id.button1);
submit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
phNo = contact.getText().toString();
new CheckOwnMobileNumber().execute();
Toast.makeText(getApplicationContext(), phNo, Toast.LENGTH_LONG).show();
}
});
}
private class CheckOwnMobileNumber extends AsyncTask<String, Void, String>
{
@Override
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
if(progress.isShowing())
{
progress.dismiss();
// Check SMS Received or not after that open dialog date
/*if(SMSReceiver.str.equals(phNo))
{
Toast.makeText(getApplicationContext(), "Thanks for providing your number.", Toast.LENGTH_LONG).show();
wasMyOwnNumber=true;workDone=true;
}
else
{
Toast.makeText(getApplicationContext(), "Provide your own mobile number please.", Toast.LENGTH_LONG).show();
wasMyOwnNumber=false;workDone=true;
return;
}*/
}
}
@Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
String msg = phNo;
try
{
sendSMS(phNo, msg);
int count=0;
while(!workDone)
{count++;}
}
catch(Exception ex)
{
Log.v("Exception :", ""+ex);
}
return null;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress = ProgressDialog.show(MainActivity.this, "","Checking Mobile Number...");
progress.setIndeterminate(true);
progress.getWindow().setLayout(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
super.onPreExecute();
}
}
private void sendSMS(String phoneNumber, String message)
{
//PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
public class SMSReceiver extends BroadcastReceiver
{
private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
Context mContext;
private Intent mIntent;
static String address, str = null;
// Retrieve SMS
public void onReceive(Context context, Intent intent) {
mContext = context;
mIntent = intent;
String action = intent.getAction();
if(action.equals(ACTION_SMS_RECEIVED))
{
SmsMessage[] msgs = getMessagesFromIntent(mIntent);
if (msgs != null)
{
for (int i = 0; i < msgs.length; i++)
{
address = msgs[i].getOriginatingAddress();
str = msgs[i].getMessageBody().toString();
}
}
// ---send a broadcast intent to update the SMS received in the
// activity---
workDone=true;
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
public static SmsMessage[] getMessagesFromIntent(Intent intent)
{
Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
byte[][] pduObjs = new byte[messages.length][];
for (int i = 0; i < messages.length; i++)
{
pduObjs[i] = (byte[]) messages[i];
}
byte[][] pdus = new byte[pduObjs.length][];
int pduCount = pdus.length;
SmsMessage[] msgs = new SmsMessage[pduCount];
for (int i = 0; i < pduCount; i++)
{
pdus[i] = pduObjs[i];
msgs[i] = SmsMessage.createFromPdu(pdus[i]);
}
return msgs;
}
}
}
Answer 5:
只是想在这里补充一点在上回答上述解释。 这将节省时间,其他人也。
在我的情况下,该方法没有返回的任何手机号码时,会返回一个空字符串。 这是因为,我已经移植上新的SIM我的电话号码的情况。 所以,如果我进入设置>关于手机>状态>我的电话号码它为我“未知”。
这可能是因为你已经移植数量从一个网络到另一个。
如果你不能够检查从API的数量则:
这样做的一种方法是你生成一个短信号码并发送生成的随机不给的手机号码。 你将不得不要求用户输入这个随机生成的数字到您的应用。 一旦在应用程序中输入,那么你可以将其发送到服务器,检查文本传递的号码是否正确(您已经保存在服务器上针对该手机号码)。
我希望这是有道理的。
文章来源: How to check user entered own phone number in EditText?