Reading OTP automatically on Android

10,689

Please use this code Create the SMS reader Broadcast receiver

public class IncomingSms extends BroadcastReceiver {

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

    // Retrieves a map of extended data from the intent.
    final Bundle bundle = intent.getExtras();

    try {

        if (bundle != null) {

            final 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().replaceAll("\\D", "");

                //message = message.substring(0, message.length()-1);
                Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);

                Intent myIntent = new Intent("otp");
                myIntent.putExtra("message", message);
                myIntent.putExtra("number", senderNum);
                LocalBroadcastManager.getInstance(context).sendBroadcast(myIntent);
                // Show Alert

            } // end for loop
        } // bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" + e);

    }
}
}

Declare class in manifest

 <receiver android:name=".receiver.IncomingSms">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

Permission in Manifest

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

Activity in which you want to fetch the SMS.

@Override
public void onResume() {
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
    super.onResume();
}
@Override
public void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equalsIgnoreCase("otp")) {
            final String message = intent.getStringExtra("message");
            // message is the fetching OTP
        }
    }
};
Share:
10,689

Related videos on Youtube

Steve Vinoski
Author by

Steve Vinoski

Erlang, distributed systems, Yaws, Emacs, C++

Updated on June 04, 2022

Comments

  • Steve Vinoski
    Steve Vinoski almost 2 years

    I am working on an Android App, in which server sends an OTP and the user needs to enter this OTP in the App, to SignUp for my App, What I want is, that my App should be able to automatically read the OTP sent by the server. .I am trying to implement auto detect OTP to edit text when OTP is received, I tried but nothing hapening any please help me to find out the error

    Readsms.class

    public class ReadSms extends BroadcastReceiver{
    
        @Override
        public void onReceive(Context context, Intent intent)
        {
    
            final Bundle bundle = intent.getExtras();
            try {
    
                if (bundle != null)
                {
    
                    final 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();
    
                        try
                        {
    
                            if (senderNum.equals("AZ-PSDSSL"))
                            {
    
                             Otp Sms = new Otp();
                                Sms.recivedSms(message );
                            }
                        } catch(Exception e){}
                    }
                }
    
            } catch (Exception e) {}
        }
    
    }
    

    Otp.class

    class Otp extends Activity {
    
    
        TextView otp;
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_otp);
             otp=findViewById(R.id.otpid);
    
        }
        public void recivedSms(String message)
        {
            try
            {
                otp.setText(message);
                Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
    
    
            }
            catch (Exception e)
            {
            }
        }
    }
    

    OTPActivity.java

    if (checkAndRequestPermissions()) {
                // carry on the normal flow, as the case of  permissions  granted.
            }
     private  boolean checkAndRequestPermissions() {
            int permissionSendMessage = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.SEND_SMS);
    
            int receiveSMS = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.RECEIVE_SMS);
    
            int readSMS = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.READ_SMS);
            List<String> listPermissionsNeeded = new ArrayList<>();
    
            if (receiveSMS != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.RECEIVE_MMS);
            }
            if (readSMS != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.READ_SMS);
            }
            if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
            }
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this,
                        listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
                        REQUEST_ID_MULTIPLE_PERMISSIONS);
                return false;
            }
            return true;
        }
    

    Manifest

    <uses-permission android:name="android.permission.INTERNET" />
    
        <uses-permission android:name="android.permission.RECEIVE_SMS" />
        <uses-permission android:name="android.permission.READ_SMS" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
         <receiver android:name=".ReadSms" >
                    <intent-filter android:priority="999" >
                        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                    </intent-filter>
                </receiver>
    
    • Lucifer
      Lucifer about 6 years
      is it giving any error in logcat ?
    • Admin
      Admin about 6 years
      no error showing in logcat
    • Lucifer
      Lucifer about 6 years
      Otp Sms = new Otp(); here you are creating a new object of your activity, so it is not working as expected. What you need to do is , you need to implement Interface to achieve, what you want.
    • Admin
      Admin about 6 years
      how is it duplicate bro? Lucifer .. if you can Answer this question using that answer
    • Lucifer
      Lucifer about 6 years
      your question is duplication of that linked one, However your actual problem is, how to send data from broadcast receiver to your activity's edittext.
    • Admin
      Admin about 6 years
      hmm qstn maybe same but method code etc are dff
  • Admin
    Admin about 6 years
    where did i add sender number ?
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    Already i have fetched the sender number with this code myIntent.putExtra("number", senderNum); in receiver class.If you want to use that sender number then you can get that number using this final String sendernumber = intent.getStringExtra("number"); in receiver method.
  • Admin
    Admin about 6 years
    i tried but not wrokd.. "AZ-PSDSSL" i want this as sender name..
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    So you are unable to fetch the otp....right?
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    can you please share the OTP message over there?
  • Admin
    Admin about 6 years
    Your OTP is 06269
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    its working fine on my side.
  • Admin
    Admin about 6 years
    Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message); i cant find these in logcat , so that is not executing .. why?
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    have you enabled the permission?
  • Admin
    Admin about 6 years
    <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
  • Admin
    Admin about 6 years
    these prmssn are there, why the class is not execting.. i didnt ad the sender number as "AZ-PSDSSL" .. did you think it is the prb?
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    if your phone version is greater than 22 then you have to allow runtime permission.
  • Admin
    Admin about 6 years
    yes, it is oreo
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    then allow the runtime permission as well. or can allow the permission for particular application in settings as well...please allow that.
  • Admin
    Admin about 6 years
    i allowed at runtime. i think the class is not executing
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    but how is that possible.because it will always run your phone got a new sms.
  • Admin
    Admin about 6 years
    yes , then why it not woking .. even logcat shows nothing .. Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    please remove the application and then again install th application...may be its working.
  • Admin
    Admin about 6 years
    i dubugg frst exexting here private BroadcastReceiver receiver = new BroadcastReceiver() {...} //receiver=null
  • Admin
    Admin about 6 years
    why you add receiver android:name=".receiver.IncomingSms"> in manifest class name is IncomingSms
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    how to know that its returning null?
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    ".receiver.IncomingSms" This is you package name where you create the Receiver.
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    It defines when you application receive any sms then this broadcast receiver call
  • Admin
    Admin about 6 years
    debugg mode value can shown in the left side,
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    is it working.?
  • Admin
    Admin about 6 years
    i create a new class named IncomingSms, <receiver android:name=".IncomingSms"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>
  • Admin
    Admin about 6 years
    no, IncomingSms class is not calling
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    Still not calling???
  • Admin
    Admin about 6 years
    IncomingSms not calling
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    Please check the log...I think some error occured.
  • Admin
    Admin about 6 years
    i want check with adding sender number, where did i add ...
  • Admin
    Admin about 6 years
    no error there in log cat
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    Then i don't know where is the issue.because its working on my phone perfectly.
  • Admin
    Admin about 6 years
    mm still not working
  • Admin
    Admin about 6 years
    if you don't mind ,can you add your work in girhub or google drive?
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    Actually i have implement this in some projects and that project is private so can't share.
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    If you can share your code with me then i'll check it and may be i can resolved the issue.
  • Admin
    Admin about 6 years
    ok i will share
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    ok thanks..I'll wait
  • Admin
    Admin about 6 years
  • Admin
    Admin about 6 years
    I creat new prjct and those things, :)
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    ok I'll check..
  • Admin
    Admin about 6 years
    thankyou i will wait
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    done..I'll share you the code.
  • Admin
    Admin about 6 years
    really thankyou so much
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    Have you check my code??
  • Admin
    Admin about 6 years
    am checking hope it will work
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    ok..let me know.
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    Have you seen where you are taking mistakes???
  • Admin
    Admin about 6 years
    yes lots of mistakes ;)
  • Saurabh Vadhva
    Saurabh Vadhva about 6 years
    Resolve your mistake and keep it up....
  • Admin
    Admin about 6 years
    ok now works charm because of you :)
  • Pramesh Bhalala
    Pramesh Bhalala almost 3 years
    can you resend the resolved code of user9427911