我知道这个问题已被多次询问但仍然无法解决我的问题。我想从Activity的editText中的短信中获取OTP。为此我使用的是广播接收器。
广播接收机代码:
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;
}
活动代码
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);
}
我使用过界面,但我总是把它作为null
。所以我能做些什么来获得otp。
P.S- 我不想通过意图启动新的Activity,因为活动只是运行,所以如果通过Intent我可以通过otp而不启动新的Activity并且还维护后台堆栈?
答案 0 :(得分:2)
如果您希望仅在活动运行时接收短信,请使用以下代码:
private void init()
{
receiveSms = new ReceiveSms();
receiveSms.setOnSmsReceivedListener(this);
registerReceiver(receiveSms, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
}
从AndroidManifest.xml中删除此接收器
我希望它对你有所帮助。
编辑:
在onDestroy中,您必须使用以下代码:
protected void onDestroy()
{
super.onDestroy();
// ...
unregisterReceiver(receiveSms);
}