I am using broadcast receiver class to read the messages automatically
But Iam facing some problems,
- I am using indent to pass the data to another activity, I do not know is this the proper approach? If any better way please let me know.
- My app automatically read the OTP from the message that was okay, but it reads every message whenever a new message arives (like customer care message and any) I want read the message only the app in running state.
Here my code,
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
String message;
@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;
message = currentMessage.getDisplayMessageBody();
Intent a = new Intent(context, OtpConformation.class);
a.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
a.putExtra("KEY_1", message);
context.startActivity(a);
}
}
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}`
In Another activity `
Intent intent = getIntent();
message = intent.getStringExtra("KEY_1");
OtpEdt = (EditText)findViewById(R.id.Otp_editText);
OtpEdt.setText(message);`
In My manifest
<receiver android:name=".IncomingSms"
android:permission="android.permission.BROADCAST_SMS">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>