Android----實現短信發送器功能

1.短信界面
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:orientation="vertical" >
  5. <EditText
  6. android:layout_width="match_parent"
  7. android:layout_height="wrap_content"
  8. android:layout_marginTop="10dp"
  9. android:hint="請輸入手機號"
  10. android:inputType="phone" />
  11. <EditText
  12. android:layout_width="match_parent"
  13. android:layout_height="wrap_content"
  14. android:layout_marginTop="10dp"
  15. android:hint="請輸入短信內容"
  16. android:inputType="text"
  17. android:lines="5" />
  18. <Button
  19. android:layout_width="wrap_content"
  20. android:layout_height="wrap_content"
  21. android:layout_marginTop="10dp"
  22. android:onClick="sendSms"
  23. android:text="發送" />
  24. </LinearLayout>
2.業務邏輯
  1. public void sendSMS(View v) {
  2. // 1.取出手機號
  3. EditText et_input_num = (EditText) findViewById(R.id.et_input_num);
  4. // trim: 過濾用戶輸入的空格
  5. String num = et_input_num.getText().toString().trim();
  6. // 2. 取出用戶輸入的短信內容
  7. EditText et_input_content = (EditText) findViewById(R.id.et_input_content);
  8. String content = et_input_content.getText().toString().trim();
  9. // 3. 校驗
  10. Pattern pattern = Pattern.compile("^1[3578]\\d{9}$");
  11. Matcher matcher = pattern.matcher(num);
  12. if (matcher.matches()) {
  13. if (content != null && !content.equals("")) {
  14. // 4. 校驗成功,發送短信
  15. SmsManager smsManager = SmsManager.getDefault();
  16. smsManager.sendTextMessage(num, null, content, null, null);
  17. } else {
  18. Toast.makeText(this, "請檢查輸入的內容", Toast.LENGTH_LONG).show();
  19. }
  20. } else {
  21. Toast.makeText(this, "請檢查手機號", Toast.LENGTH_LONG).show();
  22. }
  23. }
最後在在AndroidManifest.xml裏面添加
<uses-permission android:name="android.permission.SEND_SMS  "/>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章