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

时间:2019-03-05 08:59:34

标签: java android android-sms

我想在我的android项目中实现sms OTP接收器,这完全是用java而不是kotlin来实现的。请任何人可以帮助我使用Java语言在android中执行此操作吗?

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

1 个答案:

答案 0 :(得分:0)

尝试将其用于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"
  }
}