<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.
© 2024 OneMinuteCode. All rights reserved.