1. 程式人生 > >Android短信收發(二)

Android短信收發(二)

light undle protect ati res class cast gets new

接收SMS類,代碼如下

//for receive SMS
    private SmsReceiver mSmsReceiver;
    @Override
    protected void onResume() {
        super.onResume();
        mSmsReceiver = new SmsReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        intentFilter.setPriority(1000);
        registerReceiver(mSmsReceiver, intentFilter);
    }
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mSmsReceiver);
    }
    public class SmsReceiver extends BroadcastReceiver {
        public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG,"action: "+action);
            if (SMS_RECEIVED_ACTION.equals(action)) {
                Bundle bundle = intent.getExtras();

                //String messageContent = bundle.getString("message");
                Object[] pdus = (Object[]) bundle.get("pdus");//獲取短信數組
                SmsMessage[] messages = new SmsMessage[pdus.length];
                String format = intent.getStringExtra("format");
                for (int i = 0; i < messages.length; i++) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i],format);//將pdu字符數組轉換成SmsMessage對象
                    }
                    else {
                        messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    }
                }
                String address = messages[0].getOriginatingAddress();//獲取短信發送方的號碼
                String fullMessage = "";
                for (SmsMessage message : messages) {
                    fullMessage += message.getMessageBody();//獲取短信的內容
                }
                //sender.setText(address);
                //content.setText(fullMessage);
                Log.d(TAG,"SMS notes: "+fullMessage);
                abortBroadcast();
            }
        }
    }

  

Android短信收發(二)