<!--因爲應用要使用手機的短信服務,所以要在清單文件AndroidManifest.xml中添加短信服務權限:-->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.itcast.sms"
android:versionCode="1"
android:versionName="1.0">
略....
<uses-sdk android:minSdkVersion=“4" />
<uses-permission android:name="android.permission.SEND_SMS"/>
</manifest>
界面佈局:
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical“ android:layout_width="fill_parent“ android:layout_height="fill_parent" >
<TextViewandroid:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="@string/inputmobile"/>
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
android:id="@+id/mobile"/>
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="@string/content"/>
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
android:minLines="3"
android:id="@+id/content"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button"/>
</LinearLayout>
Activity主要代碼:
Stringmobile = mobileView.getText().toString();
Stringcontent = contentView.getText().toString();
SmsManager smsManager = SmsManager.getDefault();
PendingIntent sentIntent = PendingIntent.getBroadcast(SMSSender.this, 0, new Intent(), 0);
if(content.length()>70){//如果字數超過70,需拆分成多條短信發送
List<String> msgs =smsManager.divideMessage(content);
for(String msg : msgs){
smsManager.sendTextMessage(mobile, null, msg, sentIntent, null);
//最後二個參數爲短信已發送的廣播意圖,最後一個參數爲短信對方已收到短信的廣播意圖
}
}else{
smsManager.sendTextMessage(mobile, null, content, sentIntent, null);
}
Toast.makeText(SMSSender.this, "短信發送完成", Toast.LENGTH_LONG).show();