猿问

SMS Retriever API - 如何以编程方式获取 SMS?

我想在我的 android 项目中实现 sms OTP 接收器,它完全是在 java 而不是 kotlin 中。请任何人都可以帮助我使用java语言在android中做这件事吗?

我在我的 android 项目中尝试了 kotlin 代码,但我的 UI 功能基于 java 代码,请帮助我。


德玛西亚99
浏览 125回答 1
1回答

精慕HU

尝试将其用于 Javapublic class SmsBroadcastReceiver extends BroadcastReceiver {&nbsp; &nbsp; public static final String SMS_BUNDLE = "pdus";&nbsp; &nbsp; public void onReceive(Context context, Intent intent) {&nbsp; &nbsp; &nbsp; &nbsp; Bundle intentExtras = intent.getExtras();&nbsp; &nbsp; &nbsp; &nbsp; if (intentExtras != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String smsMessageStr = "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < sms.length; ++i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String smsBody = smsMessage.getMessageBody().toString();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String address = smsMessage.getOriginatingAddress();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; smsMessageStr += "SMS From: " + address + "\n";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; smsMessageStr += smsBody + "\n";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //this will update the UI with message&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SmsActivity inst = SmsActivity.instance();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inst.updateList(smsMessageStr);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}尝试对 Kotlin 使用类似的东西class SmsBroadcastReceiver:BroadcastReceiver() {&nbsp; fun onReceive(context:Context, intent:Intent) {&nbsp; &nbsp; val intentExtras = intent.getExtras()&nbsp; &nbsp; if (intentExtras != null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; val sms = intentExtras.get(SMS_BUNDLE) as Array<Any>&nbsp; &nbsp; &nbsp; val smsMessageStr = ""&nbsp; &nbsp; &nbsp; for (i in sms.indices)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; val smsMessage = SmsMessage.createFromPdu(sms[i] as ByteArray)&nbsp; &nbsp; &nbsp; &nbsp; val smsBody = smsMessage.getMessageBody().toString()&nbsp; &nbsp; &nbsp; &nbsp; val address = smsMessage.getOriginatingAddress()&nbsp; &nbsp; &nbsp; &nbsp; smsMessageStr += "SMS From: " + address + "\n"&nbsp; &nbsp; &nbsp; &nbsp; smsMessageStr += smsBody + "\n"&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show()&nbsp; &nbsp; &nbsp; //this will update the UI with message&nbsp; &nbsp; &nbsp; val inst = SmsActivity.instance()&nbsp; &nbsp; &nbsp; inst.updateList(smsMessageStr)&nbsp; &nbsp; }&nbsp; }&nbsp; companion object {&nbsp; &nbsp; val SMS_BUNDLE = "pdus"&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答