標籤:android android開發 傳送簡訊 sms
建立一個Android工程。
一 布局
開啟main.xml修改內容如下:
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/number" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="text" android:id="@+id/number"/> <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:inputType="text" 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" />
二 定義字串
開啟strings.xml新增內容如下:
<string name="number">請輸入手機號</string><string name="content">請輸入簡訊內容</string><string name="button">傳送簡訊</string><string name="success">發送成功</string>
三 響應點擊事件
開啟MainActivity.java,添加如下代碼:
public EditText numberText;public EditText contentText;public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState);setContentView(R.layout.main);numberText = (EditText)this.findViewById(R.id.number);contentText = (EditText)this.findViewById(R.id.contentText);Button button = (Button) this.findViewById(R.id.button);button.setOnClickListener(new ButtonClickListener());}private final class ButtonClickListener implements View.OnClickListener{ public void onClick(View v){String number = numberText.getText().toString();String content = contentText.getText().toString();SmsManager manger = SmsManager.getDefault();//分割簡訊字數,如果多餘36字分條發送 ArrayList<String> texts=manger.divideMessage(content); for(String text:texts){ // 參數:號碼,中心地址,內容,發送狀態,對方是否收到狀態 manger.sendTextMessage(number, null, text, null, null); }//簡訊發送完畢,通知使用者 Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();}}
四 添加許可權
在Manifest.xml中添加許可權:
<uses-permission android:name="android.permission.SEND_SMS"/>
android小功能實現之傳送簡訊