如何使用SmsManager傳簡訊

如果想要自己寫一個傳簡訊的App,其實非常簡單。

只需要利用SmsManager加上PendingIntent就可以辦到。
首先先設定好xml
<?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"
    >
 <EditText
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:hint="傳送到..."
     android:id="@+id/to"
    />
    <EditText
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:hint="輸入內容"
     android:id="@+id/content"
    />
    <Button
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:hint="傳送"
     android:id="@+id/send"
    />
</LinearLayout>

接下來就當使用者輸入傳送的號碼以及訊息內容, 按下button就可以傳送了。
send.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        SmsManager smsManager = SmsManager.getDefault();
        try{
            smsManager.sendTextMessage(to.getText().toString(),
            null,
            content.getText().toString(), 
            PendingIntent.getBroadcast(
            getApplicationContext(),
            0,
            new Intent(), 0),
            null);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
});

SmsManager物件第一個參數是傳入要傳送的號碼,
第三個參數是傳入要傳送的內容,
第四個參數是傳入PendingIntent的物件。

當傳送出去以後要怎麼驗證是否要送出去?
只需要再開啟另外一個模擬器, 就可以知道訊息是否有傳送到。



程式碼
http://uploadingit.com/file/2kn8o6vvkti2vj4a/SmsManagerDemo.zip