How to read SMS code from your android App
To read incoming SMS you have to do three things.
- Broadcast Receiver
- Declare Broadcast Receiver in manifest
- Need SMS Receive permissions
Note: If you are compiling against 6.0 Marshmallow
you have get android.permission.RECEIVE_SMS
at runtime. Runtime Permissions
Lets Starts Receiving incoming SMS
1) First add permissions in manifest
<uses-permission android:name="android.permission.RECEIVE_SMS" />
2) Declare Broadcast Receiver in Manifest.
What this declaration do it will inform you when ever a new SMS Receive by device.
<receiver android:name="com.example.abc.ReciveSMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
3) Add this code to your declared class in manifest
public class ReciveSMS extends BroadcastReceiver{
private SharedPreferences preferences;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null){
//---retrieve the SMS message received---
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
}
}catch(Exception e){
// Log.d("Exception caught",e.getMessage());
}
}
}
}
}
Bulu
Updated on June 23, 2022Comments
-
Bulu almost 2 years
We are looking to build the functionality in our app to read a security code that being sent as part of SMS and display on the textView. Also, I am not looking to build a broadcast receiver, may be an intent service which only will start run on a particular screen and kill the service once user navigated to another screen.
It would be great if anyone can shade some light and help with some sample code.
-
Bulu almost 8 yearsSohail thanks for answering my question. My question is around the broadcast receiver. I would like to run a background service here as the service should start only when user is on a particular screen then need to kill the service. Broadcast receiver is long running background task
-
Sohail Zahid almost 8 yearsok no problem you can register a receiver too for specific screen when jump to that screen it will recive sms when you jump out from that screen you when will not receive sms...is this work for you?
-
Huzaifa Asif over 4 yearsI have 2 sims in my phone! Is it possible to check which sim is receiving message?