我知道這個問題已被問了很多次,但仍然無法解決我的問題。我想從短信的ActivityText的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- 我不想通過意圖開始新的活動,因爲活動只是運行,所以如果通過意圖我可以通過otp而不開始新的活動,並且還維護回棧?
是否使用context.registerReceiver? – krystian71115
你在哪裏實例化smsReceived對象? –
在我的活動,但我仍然得到它爲空 –