Android提供的系统服务之--SmsManager(短信管理器)
--转载请注明出处:coder-pig
SmsManager相干介绍和使用图解:
固然为了方便各位,把代码粘1粘吧,就不用麻烦大家写代码了:
有需要的时候就复制粘贴下吧!
1)调用系统发送短信的功能:
public void SendSMSTo(String phoneNumber,String message){
//判断输入的phoneNumber是不是为合法电话号码
if(PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)){
//Uri.parse("smsto") 这里是转换为指定Uri,固定写法
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+phoneNumber));
intent.putExtra("sms_body", message);
startActivity(intent);
}
}
2)调用系统提供的短信接口发送短信:
public void sendSMS(String phoneNumber,String message){
//获得短信管理器
android.telephony.SmsManager smsManager = android.telephony.SmsManager.getDefault();
//拆分短信内容(手机短信长度限制),貌似长度限制为140个字符,就是
//只能发送70个汉字,多了要拆分成多条短信发送
//第45个参数,如果没有需要监听发送状态与接收状态的话可以写null
List<String> divideContents = smsManager.divideMessage(message);
for (String text : divideContents) {
smsManager.sendTextMessage(phoneNumber, null, text, sentPI, deliverPI);
}
}
处理发送状态的PendingIntent:
//处理返回的发送状态
String SENT_SMS_ACTION = "SENT_SMS_ACTION";
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) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "短信发送成功", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE: //普通毛病
break;
case SmsManager.RESULT_ERROR_RADIO_OFF: //无线广播被明确地关闭
break;
case SmsManager.RESULT_ERROR_NULL_PDU: //没有提供pdu
break;
case SmsManager.RESULT_ERROR_NO_SERVICE: //服务当前不可用
break;
}
}
}, new IntentFilter(SENT_SMS_ACTION));
处理接收状态的PendingIntent:
//处理返回的接收状态
String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
//创建接收返回的接收状态的Intent
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) {
Toast.makeText(context,"收信人已成功接收", Toast.LENGTH_SHORT).show();
}
}, new IntentFilter(DELIVERED_SMS_ACTION));