<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="請輸入手機號"
android:inputType="phone" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="請輸入短信內容"
android:inputType="text"
android:lines="5" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="sendSms"
android:text="發送" />
</LinearLayout>
public void sendSMS(View v) {
// 1.取出手機號
EditText et_input_num = (EditText) findViewById(R.id.et_input_num);
// trim: 過濾用戶輸入的空格
String num = et_input_num.getText().toString().trim();
// 2. 取出用戶輸入的短信內容
EditText et_input_content = (EditText) findViewById(R.id.et_input_content);
String content = et_input_content.getText().toString().trim();
// 3. 校驗
Pattern pattern = Pattern.compile("^1[3578]\\d{9}$");
Matcher matcher = pattern.matcher(num);
if (matcher.matches()) {
if (content != null && !content.equals("")) {
// 4. 校驗成功,發送短信
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(num, null, content, null, null);
} else {
Toast.makeText(this, "請檢查輸入的內容", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "請檢查手機號", Toast.LENGTH_LONG).show();
}
}