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

SMS Retriever API - how to programmatically get SMSs?

我想在我的 android 项目中实现短信 OTP 接收器,该项目完全在 java 而不是 kotlin 中。谁能帮我用 android 使用 java 语言做这件事吗?

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

尝试将此用于 Java

public class SmsBroadcastReceiver extends BroadcastReceiver {

    public static final String SMS_BUNDLE = "pdus";

    public void onReceive(Context context, Intent intent) {
        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null) {
            Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
            String smsMessageStr = "";
            for (int i = 0; i < sms.length; ++i) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

                String smsBody = smsMessage.getMessageBody().toString();
                String address = smsMessage.getOriginatingAddress();

                smsMessageStr += "SMS From: " + address + "\n";
                smsMessageStr += smsBody + "\n";
            }
            Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();

            //this will update the UI with message
            SmsActivity inst = SmsActivity.instance();
            inst.updateList(smsMessageStr);
        }
    }
}

尝试为 Kotlin 使用类似这样的东西

class SmsBroadcastReceiver:BroadcastReceiver() {
  fun onReceive(context:Context, intent:Intent) {
    val intentExtras = intent.getExtras()
    if (intentExtras != null)
    {
      val sms = intentExtras.get(SMS_BUNDLE) as Array<Any>
      val smsMessageStr = ""
      for (i in sms.indices)
      {
        val smsMessage = SmsMessage.createFromPdu(sms[i] as ByteArray)
        val smsBody = smsMessage.getMessageBody().toString()
        val address = smsMessage.getOriginatingAddress()
        smsMessageStr += "SMS From: " + address + "\n"
        smsMessageStr += smsBody + "\n"
      }
      Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show()
      //this will update the UI with message
      val inst = SmsActivity.instance()
      inst.updateList(smsMessageStr)
    }
  }
  companion object {
    val SMS_BUNDLE = "pdus"
  }
}