標籤:
一、準備字元資源
<string name="tip_phone">請輸入電話號碼</string>
<string name="tip_sms">請輸入發送資訊</string>
<string name="tip_send">發送</string>
二、頁面配置
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/tvphone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/tip_phone" />
<EditText
android:id="@+id/etphone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/tvphone"
android:inputType="phone"/>
<TextView
android:id="@+id/tvsms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/etphone"
android:text="@string/tip_sms" />
<EditText
android:id="@+id/etsms"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_below="@+id/tvsms"
android:inputType="textMultiLine"/><!—簡訊內容換行-->
<Button
android:id="@+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/etsms"
android:onClick="sendSms"
android:text="@string/tip_send"/>
</RelativeLayout>
三、具體實現代碼
public class SmsActivity extends Activity {
private EditText etphone,etsms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
//擷取電話號碼的控制項對象
etphone=(EditText) findViewById(R.id.etphone);
//擷取發送資訊的控制項對象
etsms=(EditText) findViewById(R.id.etsms);
}
public void sendSms(View v) {
switch (v.getId()) {
case R.id.sendBtn:
String phone=etphone.getText().toString();
String content=etsms.getText().toString();
//2.發簡訊的管理器對象
SmsManager smsManager=SmsManager.getDefault();
//3.拆分簡訊內容
List<String> list=smsManager.divideMessage(content);
//4.遍曆發送資訊
for(String sms:list){
//5.逐條發送資訊
smsManager.sendTextMessage(phone, null, sms, null, null);
}
//6.提示簡訊發送成功
Toast.makeText(this, "發送成功", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
四、擷取許可權
在AndroidManifest.xml中添加發簡訊的許可權
<uses-permissionandroid:name="android.permission.SEND_SMS"/>
最終效果如下:
android--簡單的發簡訊功能