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
}
}
};
Related videos on Youtube
Comments
-
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 about 6 yearsis it giving any error in logcat ?
-
Admin about 6 yearsno error showing in logcat
-
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 about 6 yearshow is it duplicate bro? Lucifer .. if you can Answer this question using that answer
-
Lucifer about 6 yearsyour 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 about 6 yearshmm qstn maybe same but method code etc are dff
-
-
Admin about 6 yearswhere did i add sender number ?
-
Saurabh Vadhva about 6 yearsAlready 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 about 6 yearsi tried but not wrokd.. "AZ-PSDSSL" i want this as sender name..
-
Saurabh Vadhva about 6 yearsSo you are unable to fetch the otp....right?
-
Saurabh Vadhva about 6 yearscan you please share the OTP message over there?
-
Admin about 6 yearsYour OTP is 06269
-
Saurabh Vadhva about 6 yearsits working fine on my side.
-
Admin about 6 yearsLog.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message); i cant find these in logcat , so that is not executing .. why?
-
Saurabh Vadhva about 6 yearshave you enabled the permission?
-
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 about 6 yearsthese 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 about 6 yearsif your phone version is greater than 22 then you have to allow runtime permission.
-
Admin about 6 yearsyes, it is oreo
-
Saurabh Vadhva about 6 yearsthen allow the runtime permission as well. or can allow the permission for particular application in settings as well...please allow that.
-
Admin about 6 yearsi allowed at runtime. i think the class is not executing
-
Saurabh Vadhva about 6 yearsbut how is that possible.because it will always run your phone got a new sms.
-
Admin about 6 yearsyes , then why it not woking .. even logcat shows nothing .. Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);
-
Saurabh Vadhva about 6 yearsplease remove the application and then again install th application...may be its working.
-
Admin about 6 yearsi dubugg frst exexting here private BroadcastReceiver receiver = new BroadcastReceiver() {...} //receiver=null
-
Admin about 6 yearswhy you add receiver android:name=".receiver.IncomingSms"> in manifest class name is IncomingSms
-
Saurabh Vadhva about 6 yearshow to know that its returning null?
-
Saurabh Vadhva about 6 years".receiver.IncomingSms" This is you package name where you create the Receiver.
-
Saurabh Vadhva about 6 yearsIt defines when you application receive any sms then this broadcast receiver call
-
Admin about 6 yearsdebugg mode value can shown in the left side,
-
Saurabh Vadhva about 6 yearsis it working.?
-
Admin about 6 yearsi create a new class named IncomingSms, <receiver android:name=".IncomingSms"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>
-
Admin about 6 yearsno, IncomingSms class is not calling
-
Saurabh Vadhva about 6 yearsStill not calling???
-
Admin about 6 yearsIncomingSms not calling
-
Saurabh Vadhva about 6 yearsPlease check the log...I think some error occured.
-
Admin about 6 yearsi want check with adding sender number, where did i add ...
-
Admin about 6 yearsno error there in log cat
-
Saurabh Vadhva about 6 yearsThen i don't know where is the issue.because its working on my phone perfectly.
-
Admin about 6 yearsmm still not working
-
Admin about 6 yearsif you don't mind ,can you add your work in girhub or google drive?
-
Saurabh Vadhva about 6 yearsActually i have implement this in some projects and that project is private so can't share.
-
Saurabh Vadhva about 6 yearsIf you can share your code with me then i'll check it and may be i can resolved the issue.
-
Admin about 6 yearsok i will share
-
Saurabh Vadhva about 6 yearsok thanks..I'll wait
-
Admin about 6 years
-
Admin about 6 yearsI creat new prjct and those things, :)
-
Saurabh Vadhva about 6 yearsok I'll check..
-
Admin about 6 yearsthankyou i will wait
-
Saurabh Vadhva about 6 yearsdone..I'll share you the code.
-
Admin about 6 yearsreally thankyou so much
-
Saurabh Vadhva about 6 yearsPlease check it over there...drive.google.com/open?id=1KXfPeFRN2dv4vBkK-LBoXDeP1V5eYbzo
-
Saurabh Vadhva about 6 yearsHave you check my code??
-
Admin about 6 yearsam checking hope it will work
-
Saurabh Vadhva about 6 yearsok..let me know.
-
Saurabh Vadhva about 6 yearsHave you seen where you are taking mistakes???
-
Admin about 6 yearsyes lots of mistakes ;)
-
Saurabh Vadhva about 6 yearsResolve your mistake and keep it up....
-
Admin about 6 yearsok now works charm because of you :)
-
Pramesh Bhalala almost 3 yearscan you resend the resolved code of user9427911