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>