Reputation: 63
I know this question has been asked many times but still i am unable to solve my problem.I want to get the OTP from the SMS in the editText of the Activity.For this i am using broadcast receiver.
Code for broadcast receiver:
private static final String TAG = ReceiveSms.class.getSimpleName();
private SmsReceivedListner smsReceived = null;
@Override
public void onReceive(Context context, Intent intent) {
//code to get sms....
Log.e(TAG, "OTP received: " + verificationCode);
if (smsReceived != null) {
smsReceived.onSmsReceived(verificationCode);
} else {
if (Constants.isLoggingEnable) {
Logger.logError(TAG, "Sms listner is null");
}
}
}
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
public void setOnSmsReceivedListener(Context context) {
this.smsReceived = (SmsReceivedListner) context;
}
Activity Code
public class EnterOtp extends MasterActivity implements View.OnClickListener, OnTaskComplete, SmsReceivedListner {
private static final String TAG = EnterOtp.class.getSimpleName();
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otp);
context = this;
init();
}
private void init() {
setUpToolbar();
receiveSms = new ReceiveSms();
receiveSms.setOnSmsReceivedListener(this);
}
I have used interface but always i am getting it as null
.So what can i do to get the otp.
P.S- I dont want to start new Activity via intent because the activity is running only, so if via Intent can i pass the otp without starting new Activity and also maintaing the back stack as well?
Upvotes: 0
Views: 1086
Reputation: 1937
If you want receive sms only when activity is running use this code:
private void init()
{
receiveSms = new ReceiveSms();
receiveSms.setOnSmsReceivedListener(this);
registerReceiver(receiveSms, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
And remove this receiver from AndroidManifest.xml
I hope it helped you.
EDIT:
In onDestroy you must use this code:
protected void onDestroy()
{
super.onDestroy();
// ...
unregisterReceiver(receiveSms);
}
Upvotes: 2