Wednesday, 17 June 2015

Reading incoming message automatically in android to verify OTP

Here I am going to explain how to read the incoming message in android automatically to verify OTP without closing the app.


Step 1).IncomingSms.class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

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("TA-DOCOMO")) 
   {
Otp Sms = new Otp();
Sms.recivedSms(message );
   }
}
catch(Exception e){}

}
  }

} catch (Exception e) 
{
                
 }
}

}



Step 2).Otp.class

   public class Otp extends Activity 
   {

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

       }   

Step 3).Add the below permissions and receiver to your manifest file


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

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