android 实例短信防火墙

2017-06-08  本文已影响0人  yanghanbin_it

短信防火墙

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
public class SMSReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("接收到短信111");

        //短信内容是封装在intent
        Bundle bundle = intent.getExtras();
        //以 pdus为键值,取出一个object数组,数组中的每一个元素,都是一条短信
        Object[] objectses = (Object[]) bundle.get("pdus");

        //拿到广播中的所有短信
        for (Object object : objectses) {
            // 通过pdus来构造短信
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) object);

            //发送的号码
            System.out.println(sms.getDisplayOriginatingAddress());
            //内容
            System.out.println(sms.getMessageBody());

            String phone = sms.getDisplayOriginatingAddress();
            if(phone.equals("110")){
                //阻止其他的广播接收者收到这条广播
                abortBroadcast();
            }
        }
    }
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.yhb.smsfilter">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".receiver.SMSReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter android:priority="1000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
            </intent-filter>
        </receiver>
    </application>

</manifest>

短信防火墙要点

上一篇 下一篇

猜你喜欢

热点阅读