简体   繁体   中英

Android broadcast receiver to scan every incoming SMS for specific Contant

I want to Scan every incoming SMS for specific content. when specific content found then a specific task is performed. suppose specific content string is "Hello world" when service find this string it will trigger a specific task ie take a photo with front camera and place that photo on a specific folder. receiver have to run always when phone is on.

Create A SMS broadcast receiver for this that gets triggered when an sms is received

public class SMSBroadcastReceiver extends BroadcastReceiver {

        private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
        private static final String TAG = "SMSBroadcastReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
             Log.i(TAG, "Intent recieved: " + intent.getAction());

                if (intent.getAction() == SMS_RECEIVED) {
                    Bundle bundle = intent.getExtras();
                    if (bundle != null) {
                        Object[] pdus = (Object[])bundle.get("pdus");
                        final SmsMessage[] messages = new SmsMessage[pdus.length];
                        for (int i = 0; i < pdus.length; i++) {
                            messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        }
                        if (messages.length > -1) {
                            Log.i(TAG, "Message recieved: " + messages[0].getMessageBody());
                        }
                    }
                }
           }
    }

Inside the receiver, you can check for the text you received and perform the particular action.

declare it in manifest also,

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

Also declare the permissions,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM