在 Android 上自动读取 OTP

Reading OTP automatically on Android

我正在开发一个 Android 应用程序,其中服务器发送一个 OTP,用户需要在应用程序中输入这个 OTP,才能注册我的应用程序,我想要的是,我的应用程序应该能够自动读取服务器发送的OTP。 .我正在尝试实现自动检测 OTP 以在收到 OTP 时编辑文本,我尝试过但没有任何结果请帮助我找出错误

Readsms.class

public class ReadSms extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent)
    {

        final Bundle bundle = intent.getExtras();
        try {

            if (bundle != null)
            {

                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                for (int i = 0; i < pdusObj.length; i++)
                {

                    SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                    String senderNum = phoneNumber ;
                    String message = currentMessage .getDisplayMessageBody();

                    try
                    {

                        if (senderNum.equals("AZ-PSDSSL"))
                        {

                         Otp Sms = new Otp();
                            Sms.recivedSms(message );
                        }
                    } catch(Exception e){}
                }
            }

        } catch (Exception e) {}
    }

}

Otp.class

class Otp extends Activity {


    TextView otp;
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_otp);
         otp=findViewById(R.id.otpid);

    }
    public void recivedSms(String message)
    {
        try
        {
            otp.setText(message);
            Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();


        }
        catch (Exception e)
        {
        }
    }
}

OTPActivity.java

if (checkAndRequestPermissions()) {
            // carry on the normal flow, as the case of  permissions  granted.
        }
 private  boolean checkAndRequestPermissions() {
        int permissionSendMessage = ContextCompat.checkSelfPermission(this,
                Manifest.permission.SEND_SMS);

        int receiveSMS = ContextCompat.checkSelfPermission(this,
                Manifest.permission.RECEIVE_SMS);

        int readSMS = ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_SMS);
        List<String> listPermissionsNeeded = new ArrayList<>();

        if (receiveSMS != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.RECEIVE_MMS);
        }
        if (readSMS != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_SMS);
        }
        if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this,
                    listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
                    REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

清单

<uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
     <receiver android:name=".ReadSms" >
                <intent-filter android:priority="999" >
                    <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                </intent-filter>
            </receiver>

请使用此代码 创建 SMS reader 广播接收器

public class IncomingSms extends BroadcastReceiver {

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

    // Retrieves a map of extended data from the intent.
    final Bundle bundle = intent.getExtras();

    try {

        if (bundle != null) {

            final Object[] pdusObj = (Object[]) bundle.get("pdus");

            for (int i = 0; i < pdusObj.length; i++) {

                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress();

                String senderNum = phoneNumber;
                String message = currentMessage.getDisplayMessageBody().replaceAll("\D", "");

                //message = message.substring(0, message.length()-1);
                Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: " + message);

                Intent myIntent = new Intent("otp");
                myIntent.putExtra("message", message);
                myIntent.putExtra("number", senderNum);
                LocalBroadcastManager.getInstance(context).sendBroadcast(myIntent);
                // Show Alert

            } // end for loop
        } // bundle is null

    } catch (Exception e) {
        Log.e("SmsReceiver", "Exception smsReceiver" + e);

    }
}
}

在清单中声明class

 <receiver android:name=".receiver.IncomingSms">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

清单中的权限

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

Activity 您要在其中获取短信。

@Override
public void onResume() {
    LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter("otp"));
    super.onResume();
}
@Override
public void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equalsIgnoreCase("otp")) {
            final String message = intent.getStringExtra("message");
            // message is the fetching OTP
        }
    }
};