发送短信

/** * 本文并非完全原创,而是基于 * http://blog.csdn.net/hotlinhao/article/details/13016425 * 来制作的修改版。感谢hotlinhao的分享。 */

// 在AndroidManifest.xml中申请权限:
<uses-permission android:name="android.permission.SEND_SMS"/>


private String LOG_TAG = "Wesnoth";
private String SENT_SMS_ACTION = "SENT_SMS_ACTION";
private String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";

/** * 发送短信 * @context 上下文对象 * @receiverNumber 收信人号码 * @text 短信内容 */
public void sendSms(Context context, String receiverNumber, String text)
{
    // 1.获取短信管理者
    SmsManager smsManager = SmsManager.getDefault();

    // 2.监听短信的发送状态。可省略这一段代码,直接sentPI = null
    Intent sentIntent = new Intent(SENT_SMS_ACTION);
    PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, sentIntent, 0);
    context.registerReceiver(new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            int resultCode = getResultCode();
            String resultInfo = null;
            switch(resultCode)
            {
                case -1 /* RESULT_OK */:
                    resultInfo = "Sms sent success.";
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    resultInfo = "Generic failure cause.";
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    resultInfo = "Failed because radio was explicitly turned off.";
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    resultInfo = "Failed because no pdu provided.";
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    resultInfo = "Failed because service is currently unavailable.";
                    break;
                case 5 /* @hide SmsManager.RESULT_ERROR_LIMIT_EXCEEDED */:
                    resultInfo = "Failed because we reached the sending queue limit.";
                    break;
                case 6 /* @hide SmsManager.RESULT_ERROR_FDN_CHECK_FAILURE */:
                    resultInfo = "Failed because FDN is enabled.";
                    break;
                default:
                    resultInfo = "Error: Unexpected result code.";
                    break;
            }
            Log.d(LOG_TAG, resultInfo);
        }
    }, new IntentFilter(SENT_SMS_ACTION));

    // 3.监听短信是否已送达。可省略这一段代码,直接deliverPI = null
    Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
    PendingIntent deliverPI = PendingIntent.getBroadcast(context, 0, deliverIntent, 0);
    context.registerReceiver(new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            Log.d(LOG_TAG, "Destination address got Sms.");
        }
    }, new IntentFilter(DELIVERED_SMS_ACTION));

    // 4.发送短信
    smsManager.sendTextMessage(phoneNumber, null, text, sentPI, deliverPI);
}

你可能感兴趣的:(发送短信)