回 Android手機程式設計人才培訓班 課程時間表

手機撥號、發送、接收簡訊

手機撥號

需要權限:android.permission.CALL_PHONE

透過手機內建撥號程式撥號只需要透過Intent物件,並將電話號碼放到Intent物件內後startActivity()即可。

範例:
// 需要權限:android.permission.CALL_PHONE
public static void callPhone(Context context, String number)
{
    Intent it = new Intent("android.intent.action.CALL", Uri.parse("tel:" + number));

    // 明確指定使用內建的撥號器,否則如有安裝其它撥號軟體(如skype),將會跳出選擇畫面
    it.setPackage("com.android.phone");
    context.startActivity(it);
}
如果沒有明確指定撥號器的話,將可能會跳出裝致內所有可以撥號的程式清單讓使用者選擇(例如:Skype等等)。

發送簡訊

需要權限:android.permission.SEND_SMS

透過取得系統物件SmsManagersendTextMessage()方法,可以發送一般文字簡訊 範例:

public static void sendSms(Context context, String number, String message)
{
    // 取得SmsManager
    SmsManager sm = SmsManager.getDefault();

    try
    {
        sm.sendTextMessage(number,  // 要送出簡訊的電話
                           null,    // 電話號碼位址
                           message, // 簡訊內容
                           null,    // 發送簡訊结果(是否成功發送),需使用PendingIntent
                           null);   // 對方接收結果(是否已成功接收),需使用PendingIntent

        Toast.makeText(context, "發送簡訊到" + number, Toast.LENGTH_SHORT).show();
    }
    catch(Exception e)  // 如果發送錯誤或其他錯誤發生
    {
        Toast.makeText(context, "發送簡訊到" + number + "失敗。", Toast.LENGTH_SHORT).show();
    }
}

如果你想要知道簡訊的發送成功與否,或是是否有成功送達對方,你可以準備好PendingIntent,系統會透過廣播(Broadcast)的方式來將結果的Intent物件廣播出去,然後我們可以透過建立IntentFilter來過濾出我們想要收到的Intent

例如:
private void sendSMS(String phoneNo, String message)
{      
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";

    // 簡訊傳送結果的PendingIntent
    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);

    // 對方接收結果的PendingIntent
    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);

    registerReceiver(new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context arg0, Intent arg1) 
        {
            switch (getResultCode())
            {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS sent", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(getBaseContext(), "Generic failure", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(getBaseContext(), "No service", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(getBaseContext(), "Null PDU", Toast.LENGTH_SHORT).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(getBaseContext(), "Radio off", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }, new IntentFilter(SENT));

    registerReceiver(new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context arg0, Intent arg1) 
        {
            switch (getResultCode())
            {
            case Activity.RESULT_OK:
                Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_SHORT).show();
                break;
            case Activity.RESULT_CANCELED:
                Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_SHORT).show();
                break;                      
            }
        }
    }, new IntentFilter(DELIVERED));        

    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI);               
}
如果你要傳送的簡訊超過160的英文字或80個中文字,你必須先呼叫divideMessage()來將簡訊切割後會取得一個ArrayList,然後改用sendMultipartTextMessage()方法來傳送簡訊。

接收簡訊

需要權限:android.permission.RECEIVE_SMS

步驟一:在AndroidManifest.xml中的Application元素中設定receiver

<receiver
    android:name=".MySMSReceiver"
    android:enabled="true" >
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

步驟二:加入BroadcastReceiver類別

public class MySMSReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Bundle bundle = intent.getExtras();

        if (bundle == null)
            return;
        
        Object[] pdus = (Object[])bundle.get("pdus");

        for(int i = 0 ; i < pdus.length ; i++) 
        {
            SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
            String fromAddress = message.getOriginatingAddress();

            String msg = message.getMessageBody();
            
            // 判斷是不是自己要的簡訊
            if(msg.startsWith("aaronlife")) 
            {
                abortBroadcast(); // 停止發送廣播給其它app

                // 其它處理該簡訊的程式碼
                ...
            }
        }
    }
}