27
2017
09

Android发送短信

(1)权限

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

(2)获取SMSManager

SmsManager mSMSManager=SmsManager.getDefault();

(3)发送消息

SMSManager依据信息的长度,将信息拆分成多条消息发送出去。

List<String> divideContents = mSMSManager.divideMessage(message);
for (String text : divideContents) { mSMSManager.sendTextMessage(destinationAddress, scAddress, text, sentIntent, DeliveryIntent); }

对于SendTextMessage方法,
destinationAddress:收信人的手机号码
scAddress:服务中心的地址。为空则使用当前默认的SMSC。
text:发送信息的内容
sentIntent:发送是否成功的回执,用于监听短信是否发送成功。
DeliveryIntent:接收是否成功的回执,用于监听短信对方是否接收成功。

(4)消息发送监听sentIntent(Optional)

可以不设置监听,在sendTextMessage设置null

String SENT_SMS_ACTION = "SENT_SMS_ACTION";
Intent sentIntent = new Intent(SENT_SMS_ACTION);
mSentPI = PendingIntent.getBroadcast(mContext, 0, sentIntent, 0);
registerReceiver(new BroadcastReceiver() {
    @Override
    public void onReceive(Context _context, Intent _intent) {
        switch (getResultCode()) {
            case Activity.RESULT_OK:
                //TODO, For Send Success
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                break;
        }
    }
}, new IntentFilter(SENT_SMS_ACTION));

(5)消息接收监听DeliveryIntent(Optional)

可以不设置监听,在sendTextMessage设置null

String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
mDeliverIntent = PendingIntent.getBroadcast(mContext, 0,deliverIntent, 0);
mContext.registerReceiver(new BroadcastReceiver() {
    @Override
    public void onReceive(Context _context, Intent _intent) {
        //TODO,for recevice message.
    }
}, new IntentFilter(DELIVERED_SMS_ACTION));
上一篇:Log搜集工具软件文档梳理 下一篇:ruby库xcodeproj使用心得