2015年4月21日 星期二

【Android】利用BroadcastReceiver來監聽是否收到簡訊

1. AndroidManifest.xml

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

2. 在Application中註冊Receiver:

      <!-- use SMS receiver-->
        <receiver
            android:name="soonsource.sms.SMSReceiver"
            android:enabled="false">
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>


3. java code :  Receiver class 程式碼


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;


public class SMSReceiver extends BroadcastReceiver {

    static final String TAG = "SMSReceive";
    static final String smsuri = "android.provider.Telephony.SMS_RECEIVED";

    private static final String queryString = "xxxx:";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(smsuri)) {

            Bundle bundle = intent.getExtras();

            if (null != bundle) {

                Object[] pdus = (Object[]) bundle.get("pdus");
                SmsMessage[] smg = new SmsMessage[pdus.length];

                for (int i = 0; i < pdus.length; i++) {
                    smg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    Log.i(TAG + "smg" + i, smg[i].toString());
                }
                for (SmsMessage cursmg : smg) {

                    String displayMessageBody = cursmg.getDisplayMessageBody();
                    String displayOriginatingAddress = cursmg.getDisplayOriginatingAddress();
                    String messageBody = cursmg.getMessageBody();
                    String originatingAddress = cursmg.getOriginatingAddress();
                    Log.i(TAG + "displayMessageBody:", displayMessageBody);
                    Log.i(TAG + "displayOriginatingAddress:", displayOriginatingAddress);
                    Log.i(TAG + "messageBody:", messageBody);
                    Log.i(TAG + "originatingAddress:", originatingAddress);

                }

                abortBroadcast(); //終止此條廣播
            }
        }
    }
}



4. 一般來說不會一直開著監聽,預設都是關掉

  AndroidManifest.xml 設定 (第2點中的  android:enable設為false),然後再利用啟動服務的的方式打開,收到資料後再關掉。



5. 開啟監聽

        final PackageManager pm = this.getPackageManager();
        final ComponentName componentName = new ComponentName(this, SMSReceiver.class);
        pm.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);



沒有留言:

張貼留言