转载地址:http://blog.sina.com.cn/s/blog_613e4fea0100oj3m.html
Android系统提供了Intent方法,来实现短信接口的调用。使用startActivity()启动了了短信功能后,短信界面就会呈现在用户面前。开发其他应用程序用此方法,就显得不太合理。在这里总结使用源码来完成短信发送任务,很多代码都来自网上,在这里,我仅做了点封装。
由于在MSM短信是在后台发送的,取名为sendTextMsgBack()。
void sendTextMsgBack(Context_context, //函数调用者
String_strDestAddress, //收件人号码
String_strMessage){ //短信内容
//当消息发送成功或发送失败时触发
Intent sentIntent=new Intent(SENT_SMS_ACTION);
PendingIntent sentPI=PendingIntent.getBroadcast(_context, 0,sentIntent, 0);
//仅在当目标用户接收到你的SMS消息后触发
Intent deliverIntent=new Intent(DELIVERED_SMS_ACTION);
PendingIntent deliverPI=PendingIntent.getBroadcast(_context, 0,deliverIntent, 0);
SmsManager sms = SmsManager.getDefault();
if (_strMessage.length() > 70) {
ArrayList<String> msgs =sms.divideMessage(_strMessage);
for (String msg : msgs) {
sms.sendTextMessage(_strDestAddress, null, msg,sentPI, deliverPI);
}
}else {
sms.sendTextMessage(_strDestAddress, null, _strMessage, sentPI,deliverPI);
}
}
为了监视短信的发送状态,另外还需要两个广播接收器。
finalString SENT_SMS_ACTION = "SENT_SMS_ACTION";
final StringDELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
privateclass SMS_BroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//System.out.println("SMS_BroadcastReceiver");
switch(getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent success actions",
Toast.LENGTH_SHORT).show();
System.out.println("SMS sent successactions");
break;
caseSmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "SMS generic failureactions",
Toast.LENGTH_SHORT).show();
System.out.println("SMS generic failure actions");
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(),
"SMS radio off failure actions", Toast.LENGTH_SHORT).show();
System.out.println("SMS radio off failure actions");
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(),
"SMS null PDU failure actions", Toast.LENGTH_SHORT).show();
System.out.println("SMS null PDU failure actions");
break;
}
}
}
privateclass Dele_BroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context _context,Intent _intent){
Toast.makeText(getBaseContext(),
"SMS delivered actions",
Toast.LENGTH_SHORT).show();
System.out.println("SMS delivered actions");
}
}
在Activity对象里,对这两个广播接收器进行注册。
另外,在提供个对Intent方法发送短信的函数封装:
voidsendTextMsgFont(Context _context, //函数调用者
String_strDestAddress, //收件人号码
String_strMessage){ //短信内容
Uri uri =Uri.parse( "smsto:" + _strDestAddress);
Intent it = new Intent(Intent.ACTION_SENDTO,uri);
it.putExtra("sms_body", _strMessage);
_context.startActivity(it);
}