2012年1月17日 星期二

【Android】TQC+題組系列3(四)


考完了,沒考過所以這應該是最後一篇了,到現在還沒搞懂實作的分數都被扣到哪去了,anyway...

首先是在SMS註冊receiver還有權限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="COM.TQC.GDD03" android:versionCode="1" android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".GDD03" 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="GDD03_SM_Receiver">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

    </application>
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
</manifest> 

然後是BroadcastReceiver的內容,固定寫法就背吧
public class GDD03_SM_Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        if (!intent.getAction().equals(
                "android.provider.Telephony.SMS_RECEIVED"))
            return;
        Object[] pdus = (Object[]) intent.getExtras().get("pdus");
        SmsMessage[] messages = new SmsMessage[pdus.length];
        for (int i = 0; i < messages.length; i++)
            messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);

        String msg = "";
        for (SmsMessage message : messages) {
            msg += "接到來自:\n" + message.getDisplayOriginatingAddress();
            msg += "\n-----傳來的簡訊-----\n" + message.getDisplayMessageBody();

        }

        Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
    }
}

沒有留言:

張貼留言