Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send and receive sms to verify mobile number

Tags:

java

android

I am trying to do mobile number verification without using third party. For this my logic is this:-

  • User enter their mobile number with country code
  • When they click on verify button a intent will send a sms to user-defined mobile number with random unique id
  • after that app broadcast will wait for 2 minute and when it receive sms then user can login or sign-up

Is this logic right or it need some modification?

To send sms i am using this code, but dont know how i can recieve and validate number.

 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);

UPDATE:-

Not receiving message on samsung device.

this requires android.permission.INTERACT_ACROSS_USERS_FULL

like image 261
neo Avatar asked Jan 08 '23 01:01

neo


1 Answers

First I generate a random number within range 10000 to 99999.

 Random rNo = new Random();
 final int code = rNo.nextInt((99999 - 10000) + 1) + 10000;

Next I display a popup mentioning the user that a message will be sent from the mobile to verify the number. This is done using 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();

Explanation of above code:

After user acknowledges to send sms an sms is sent with the code to the entered number and this number should be the one that user is using himself. So we will wait for an sms with the code, to receive the sms and read its content we will create a BroadCastReceiver to listen to incoming sms.

Now also we need to start a timer so that we wait for only 2 minutes for the sms, so we start a CountDownTimer for 2 minutes at the end of 2 minutes the countdowntimer will unregister the receiver. The receiver is unregistered even if the code is received in the incoming sms so that we can free the resources.

Code to readSMS, if the code is found true is returned else false is returned,

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;
    }

To send SMS use below method:

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 + "");
        }
    }

In AndroidManifest.xml you need to have these permissions:

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
like image 190
Psypher Avatar answered Jan 16 '23 18:01

Psypher