1

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

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

4

1 回答 1

1

尝试将其用于 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"
  }
}
于 2019-03-05T09:03:40.883 回答