How to 'listen' to see if SMS arrived on Android

1

I'm implementing a Two-Factor Authentication service where I use a gateway to send validation codes to the user's registry. I want to implement an automatic check on the android to see if the message has arrived on the user's device and does not require him to enter the code and then go to validate the code because this check in the API has a cost.     

asked by anonymous 17.07.2016 / 01:51

1 answer

1

Here's an example:

Add the following permissions to your AndroidManifest.xml :

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

Still in the manifest, add the following receiver (inside the application tag):

<receiver android:name=“seu.pacote.IncomingSMS">   
    <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
  </receiver>

IncomingSMS.java

public class IncomingSMS extends BroadcastReceiver {


    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 message = currentMessage.getDisplayMessageBody();

                    Log.i("SmsReceiver", "senderNum: "+ phoneNumber + "; message: " + message);

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

        }
    }
}
    
18.07.2016 / 14:48