2015年4月21日 星期二

【Android】在 activtiy中使用 BroadcastReceiver 接收簡訊(SMS)

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


  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xxxxxxx);

        // BroadcastReceiver
        registerReceiver(mBroadcastReceiver,new IntentFilter(MSG_RECEIVED));

    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context arg0, Intent intent) {
            // TODO Auto-generated method stub
            if (intent.getAction().equals(MSG_RECEIVED)) {

                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);

                    }

                    smsMsgFinish();

                }
            }
        }
    };

    private void smsMsgFinish() {

        new AlertDialog.Builder(this)
                .setMessage("收到訊息!")
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 將註冊解除
                        unregisterReceiver(mBroadcastReceiver);
                    }
                })
                .show();
    }

沒有留言:

張貼留言