Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 短信發送功能實作範例

編輯:關於 Android 程式設計

在 Android 應用開發中,發送手機短信是很常見的需求。對 Android 平台來說這是最簡單的功能之一:不需要太多程式碼,也不必自訂底層實作,只要調用系統提供的 SmsManager 即可。

核心程式碼僅僅三行:

SmsManager sms = SmsManager.getDefault();
PendingIntent intent = PendingIntent.getBroadcast(MainActivtiy.this, 0, new Intent(), 0);
sms.sendTextMessage(phone.getText().toString(), null, text.getText().toString(), intent, null);

下面一步步把這個功能做出來。

第 1 步:建立 Activity

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivtiy extends Activity {
    EditText text;
    EditText phone;
    Button send;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        send = (Button) findViewById(R.id.send);
        text = (EditText) findViewById(R.id.text);
        phone = (EditText) findViewById(R.id.phone);
        send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SmsManager sms = SmsManager.getDefault();
                PendingIntent intent = PendingIntent.getBroadcast(MainActivtiy.this, 0, new Intent(), 0);
                sms.sendTextMessage(phone.getText().toString(), null, text.getText().toString(), intent, null);
                Toast.makeText(MainActivtiy.this, "發送成功.....", Toast.LENGTH_LONG).show();
            }
        });
    }
}

第 2 步:編寫佈局 main.xml




    

    

    

第 3 步:加入權限宣告

在 AndroidManifest.xml 中加入發送短信的權限:

第 4 步:編譯運行

幾點實務提醒:sendTextMessage 的第二個參數是散射地址,一般傳 null 即可;第五個參數是發送結果的 PendingIntent,若需要在真實設備上確認發送是否成功,建議補上並搭配 BroadcastReceiver 處理。另外,自 Android 6.0 起 SEND_SMS 屬於危險權限,除了宣告之外還必須在執行期動態向使用者申請。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved