How to read text messages from Android

Asked 2 years ago, Updated 2 years ago, 52 views

I'd like to send a text message with the authentication number when I sign up for membership and automatically remove the authentication number from the app. In order to do that, you need to get a sms. How can I get the contents of sms?

android sms

2022-09-22 16:51

1 Answers

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

public class SMSReceiver extends BroadCastReceiver {

    // The method that is performed when a specified action occurs 
    @Override
    public void onReceive(Context context, Intent intent) {

        // Insert if statement to respond only when SMS is received
        if (intent.getAction().equals(
            "android.provider.Telephony.SMS_RECEIVED")) {
            StringBuilder sms = new StringBuilder(); // Where to store SMS characters
            Bundle bundle = int.getExtras(); // Receives text to Bundle object

            if (bundle != null) {
                // Receives character data contained in the bundle as an object array
                Object[] pdusObj = bundle.get("pdus");

                // Create an array of sms messages to receive SMS
                SmsMessage[] messages = new SmsMessage[pdusObj.length];
                for (int i = 0; i < pdusObj.length; i++) {
                    messages[i] =
                        SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    // CreateFromPdu, the static method of SmithMessage, is pdusObj's
                    // Put the data in the message
                    // At this time, pdusObj needs to be transformed into a byte array
                }

                // Save data in SmsMessage array to sms as append method
                for (SmsMessage smsMessage : messages) {
                    // The getMessageBody method is a method for receiving text bodies
                    sms.append(smsMessage.getMessageBody());
                }

                sms.toString() // Convert StringBuilder object sms to String
            }   
        }
    }
}
    <receiver android:name=".SMSReceiver">
        <intent-filter >
            <!-- Add an int-filter to retrieve text -->
            <action android:name="android.provider.Telephony.SMS_RECEIVED"/>                
        </intent-filter>
    </receiver>

You can apply this well.


2022-09-22 16:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.