文章目錄
有兩種方法可以實現傳送簡訊,其一是使用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);
其二是使用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.CALL_PHONE"/>
向模擬器發簡訊打電話的方法
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為模擬器手機號碼。