androidandroid-layoutandroid-activityandroid-broadcastreceiver

Automatic OTP verification lollipop


I am working on verifying the OTP automatically. In the versions lower than lollipop, it is working perfectly But it doesn't work in 5.0 and above I tried the code from the tutorial. Here is the code:

IncomingSMS.java

  public class IncomingSms 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("+917760882587"))
                        {
                            MainActivity Sms = new MainActivity();
                            Sms.recivedSms(message );
                        }
                    }
                    catch(Exception e){}

                }
            }

        } catch (Exception e)
        {

        }
    }

}

MainActivity.java

    public class MainActivity extends AppCompatActivity {

    static EditText OtpNumber;
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        OtpNumber= (EditText) findViewById(R.id.editText);
    }
    public void recivedSms(String message)
    {
        try
        {
            OtpNumber.setText(message);
        }
        catch (Exception e)
        {
        }
    }

}

Can anyone help why is it not working for lollipop and above devices?


Solution

  • Change this code only :-

    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[])pdusObj[i]);