Android利用廣播攔截簡訊

我叫阿狸貓發表於2014-02-10

接收簡訊廣播的接收者

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;

public class SmsRecever extends BroadcastReceiver {

	public void onReceive(Context context, Intent intent) {
		//獲取簡訊資料(多段)
		Object[] pdus = (Object[]) intent.getExtras().get("pdus");
		for (Object pdu : pdus) {
			//把位元組資料封裝成SmsMessage物件
			SmsMessage sms = SmsMessage.createFromPdu((byte[])pdu);
			String address = sms.getOriginatingAddress();
			String body = sms.getMessageBody();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date(sms.getTimestampMillis());
			dateFormat.format(date);
			
			System.out.println(date+" "+address+" "+body);
			if("13666666666".equals(address)){
				abortBroadcast();//進行廣播攔截
			}
		}
	}
}
清單檔案

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xxc.blacklist"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
    <!-- 配置接收簡訊許可權 -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        
        <receiver android:name="SmsRecever">
            <intent-filter android:priority="1">
                <!-- 配置接收的廣播動作 -->
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>


相關文章