有兩種方法可以實現發送短信,其一是使用intent-startActivity,URI數據格式爲"smsto:num",調用的action爲Intent.ACTION_SENDTO:
Uri uri = Uri.parse("smsto:5554");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "你好。。");
startActivity(it);
// Intent intent = new Intent(Intent.ACTION_VIEW);
// intent.setType("vnd.android-dir/mms-sms");
// intent.putExtra("sms_body", body);
其二是使用SmsManager:
EditText num=(EditText)findViewById(R.id.num);
EditText content=(EditText)findViewById(R.id.content);
String mobile=num.getText().toString();
String smstext=content.getText().toString();
//獲取SmsManager
SmsManager sms=SmsManager.getDefault();
//如果內容大於70字,則拆分爲多條
List<String> texts=sms.divideMessage(smstext);
//逐條發送短信
for(String text:texts)
{
sms.sendTextMessage(mobile, null, text, null, null);
}
//發送結果提示
Toast.makeText(SendSMS.this, "發送成功", Toast.LENGTH_LONG).show();
二者的不同在於前者只是調用了發送界面,需要按下Send按鈕短信才發送出去,而後者則是直接發送出去。
發送SMS權限的設置:
<uses-permission android:name="android.permission.SEND_SMS"/>
關於SmsManager
SDK中的介紹:Manages SMS operations such as sending data, text, and pdu SMS messages. Get this object by calling the static method SmsManager.getDefault().
方法:
public void sendTextMessage (String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)
destinationAddress: 收件人地址
scAddress: 短信中心號碼,null爲默認中心號碼
sentIntent: 當消息發出時,成功或者失敗的信息報告通過PendingIntent來廣播。如果該參數爲空,則發信程序會被所有位置程序檢查一遍,這樣會導致發送時間延長。
deliveryIntent: 當消息發送到收件人時,該PendingIntent會被廣播。pdu數據在狀態報告的extended data ("pdu")中。
如果收件人或者信息爲空則拋出 IllegalArgumentException 。
public ArrayList<String> divideMessage (String text)
將大於70字的短信分割爲多條。
參數:text the original message. Must not be null.
返回:an ArrayList of strings that, in order, comprise the original message
sendDataMessage 參數與上類似,只是用於發送Data。
sendMultipartTextMessage發送多條短信,發送內容必須是用divideMessage分割好了的。
打電話的方法
打電話的方法類似,所不用的是URI格式爲"tel:num",而調用的action爲Intent.ACTION_CALL:
EditText edit=(EditText)findViewById(R.id.DialEdit);
String num=edit.getText().toString();
if((num!=null)&&(!"".equals(num.trim())))
{
Intent intent=new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+num));
startActivity(intent);
}
打電話權限的設置:
<uses-permission android:name="android.permission.SEND_SMS"/>
向模擬器發短信打電話的方法
1.啓動android emulator,查看標題欄找出端口。一般是android emulator (5554),其中5554就是端口。
2.打開命令行,輸入telnet localhost 5554。程序將會連接到android console,返回
Android Console: type 'help' for a list of commands
OK
模擬電話打入gsm <call|accept|busy|cancel|data|hold|list|voice|status>
輸入gsm call <模擬打進的電話號碼>。如:
gsm call 15555218135
模擬短信發送sms send <senderPhoneNumber> <textmessage>
輸入sms send <模擬發送短信的電話> <內容>。如:
sms send 15555218135 hello
其中,15555218135爲模擬器手機號碼。
轉自:http://www.cnblogs.com/feisky/archive/2010/06/10/1755914.html