• Android Video Tutorials

Android - 傳送簡訊



在 Android 中,您可以使用 SmsManager API 或裝置內建的簡訊應用傳送簡訊。在本教程中,我們將向您展示兩個傳送簡訊的基本示例:

SmsManager API

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

內建簡訊應用

Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content"); 
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);

當然,兩者都需要 **SEND_SMS 許可權**。

<uses-permission android:name="android.permission.SEND_SMS" />

除了上述方法外,SmsManager 類中還提供了一些其他重要功能。這些方法列出如下:

序號 方法和描述
1

ArrayList<String> divideMessage(String text)

此方法將簡訊文字分成多個片段,每個片段都不大於最大簡訊大小。

2

static SmsManager getDefault()

此方法用於獲取 SmsManager 的預設例項。

3

void sendDataMessage(String destinationAddress, String scAddress, short destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent deliveryIntent)

此方法用於將基於資料的簡訊傳送到特定的應用程式埠。

4

void sendMultipartTextMessage(String destinationAddress, String scAddress, ArrayList<String> parts, ArrayList<PendingIntent> sentIntents, ArrayList<PendingIntent> deliveryIntents)

傳送多部分文字簡訊。

5

void sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)

傳送文字簡訊。

示例

以下示例將向您演示如何使用 SmsManager 物件將簡訊傳送到指定的手機號碼。

要體驗此示例,您需要配備最新 Android 作業系統的實際移動裝置,否則您將不得不使用模擬器,而模擬器可能無法正常工作。
步驟 描述
1 您將使用 Android Studio IDE 建立一個 Android 應用程式,並將其命名為 *tutorialspoint*,位於包 *com.example.tutorialspoint* 下。
2 修改 *src/MainActivity.java* 檔案,並新增所需的程式碼來處理傳送簡訊。
3 修改佈局 XML 檔案 *res/layout/activity_main.xml*,新增所需的任何 GUI 元件。我將新增一個簡單的 GUI 來獲取手機號碼和要傳送的簡訊文字,以及一個傳送簡訊的簡單按鈕。
4 無需在 res/values/strings.xml 中定義預設字串常量。Android Studio 會處理預設常量。
5 修改 *AndroidManifest.xml*,如下所示
6 執行應用程式以啟動 Android 模擬器並驗證對應用程式所做的更改的結果。

以下是修改後的主活動檔案 **src/com.example.tutorialspoint/MainActivity.java** 的內容。

package com.example.tutorialspoint;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Activity;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsManager;

import android.util.Log;
import android.view.Menu;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
   private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;
   Button sendBtn;
   EditText txtphoneNo;
   EditText txtMessage;
   String phoneNo;
   String message;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      sendBtn = (Button) findViewById(R.id.btnSendSMS);
      txtphoneNo = (EditText) findViewById(R.id.editText);
      txtMessage = (EditText) findViewById(R.id.editText2);

      sendBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            sendSMSMessage();
         }
      });
   }
	
   protected void sendSMSMessage() {
      phoneNo = txtphoneNo.getText().toString();
      message = txtMessage.getText().toString();
		
      if (ContextCompat.checkSelfPermission(this,
         Manifest.permission.SEND_SMS)
         != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
               Manifest.permission.SEND_SMS)) {
            } else {
               ActivityCompat.requestPermissions(this,
                  new String[]{Manifest.permission.SEND_SMS},
                  MY_PERMISSIONS_REQUEST_SEND_SMS);
            }
      }
   }
	
   @Override
   public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
      switch (requestCode) {
         case MY_PERMISSIONS_REQUEST_SEND_SMS: {
            if (grantResults.length > 0
               && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  SmsManager smsManager = SmsManager.getDefault();
                  smsManager.sendTextMessage(phoneNo, null, message, null, null);
                  Toast.makeText(getApplicationContext(), "SMS sent.", 
                     Toast.LENGTH_LONG).show();
            } else {
               Toast.makeText(getApplicationContext(), 
                  "SMS faild, please try again.", Toast.LENGTH_LONG).show();
               return;
            }
         }
      }

   }
}

以下是 **res/layout/activity_main.xml** 檔案的內容:

這裡 abc 指的是 tutorialspoint 的 logo
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context="MainActivity">

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Sending SMS Example"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials point "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_below="@+id/textView1"
      android:layout_alignRight="@+id/imageButton"
      android:layout_alignEnd="@+id/imageButton" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />
      
   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText"
      android:hint="Enter Phone Number"
      android:phoneNumber="true"
      android:textColorHint="@color/abc_primary_text_material_dark"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true" />

   <EditText
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/editText2"
      android:layout_below="@+id/editText"
      android:layout_alignLeft="@+id/editText"
      android:layout_alignStart="@+id/editText"
      android:textColorHint="@color/abc_primary_text_material_dark"
      android:layout_alignRight="@+id/imageButton"
      android:layout_alignEnd="@+id/imageButton"
      android:hint="Enter SMS" />

   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Send Sms"
      android:id="@+id/btnSendSMS"
      android:layout_below="@+id/editText2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="48dp" />

</RelativeLayout>

以下是 **res/values/strings.xml** 的內容,用於定義兩個新的常量:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">tutorialspoint</string>
</resources>

以下是 **AndroidManifest.xml** 的預設內容:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint" >
  
   <uses-permission android:name="android.permission.SEND_SMS" />
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.tutorialspoint.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

讓我們嘗試執行您的 **tutorialspoint** 應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟專案的某個活動檔案,然後單擊工具欄中的執行 Eclipse Run Icon 圖示。在啟動應用程式之前,Android Studio 安裝程式將顯示以下視窗,以選擇您要執行 Android 應用程式的位置。

Android Mobile Device

現在,您可以輸入所需的手機號碼和要傳送到該號碼的簡訊。最後,單擊“傳送簡訊”按鈕傳送簡訊。確保您的 GSM/CDMA 連線正常工作,以便將簡訊傳遞給收件人。

您可以輸入多個以逗號分隔的簡訊號碼,然後在程式中將它們解析為字串陣列,最後可以使用迴圈將簡訊傳送到所有指定的號碼。這就是您可以編寫自己的簡訊客戶端的方式。下一節將向您展示如何使用現有的簡訊客戶端傳送簡訊。

使用內建意圖傳送簡訊

您可以使用 Android 意圖透過呼叫 Android 的內建簡訊功能來發送簡訊。以下部分解釋了傳送簡訊所需的意圖物件的各個部分。

意圖物件 - 傳送簡訊的動作

您將使用 **ACTION_VIEW** 動作啟動安裝在 Android 裝置上的簡訊客戶端。以下是使用 ACTION_VIEW 動作建立意圖的簡單語法。

Intent smsIntent = new Intent(Intent.ACTION_VIEW);

意圖物件 - 傳送簡訊的資料/型別

要傳送簡訊,您需要使用 setData() 方法指定 **smsto:** 作為 URI,並將資料型別設定為 **vnd.android-dir/mms-sms**,如下所示:

smsIntent.setData(Uri.parse("smsto:"));
smsIntent.setType("vnd.android-dir/mms-sms");

意圖物件 - 傳送簡訊的額外資訊

Android 內建支援新增電話號碼和簡訊以傳送簡訊,如下所示:

smsIntent.putExtra("address"  , new String("0123456789;3393993300"));
smsIntent.putExtra("sms_body"  , "Test SMS to Angilla");
這裡 address 和 sms_body 區分大小寫,並且應僅使用小寫字元指定。您可以在單個字串中指定多個號碼,但需要用分號 (;) 分隔。

示例

以下示例將向您演示如何使用意圖物件啟動簡訊客戶端,以將簡訊傳送到指定的收件人。

要體驗此示例,您需要配備最新 Android 作業系統的實際移動裝置,否則您將不得不使用模擬器,而模擬器可能無法正常工作。
步驟 描述
1 您將使用 Android Studio IDE 建立一個 Android 應用程式,並將其命名為 *tutorialspoint*,位於包 *com.example.tutorialspoint* 下。
2 修改 *src/MainActivity.java* 檔案,並新增所需的程式碼來處理傳送簡訊。
3 修改佈局 XML 檔案 *res/layout/activity_main.xml*,新增所需的任何 GUI 元件。我將新增一個簡單的按鈕來啟動簡訊客戶端。
4 無需定義預設常量。Android Studio 會處理預設常量。
5 修改 *AndroidManifest.xml*,如下所示
6 執行應用程式以啟動 Android 模擬器並驗證對應用程式所做的更改的結果。

以下是修改後的主活動檔案 **src/com.example.tutorialspoint/MainActivity.java** 的內容。

package com.example.tutorialspoint;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      Button startBtn = (Button) findViewById(R.id.button);
      startBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
            sendSMS();
         }
      });
   }
   
   protected void sendSMS() {
      Log.i("Send SMS", "");
      Intent smsIntent = new Intent(Intent.ACTION_VIEW);
      
      smsIntent.setData(Uri.parse("smsto:"));
      smsIntent.setType("vnd.android-dir/mms-sms");
      smsIntent.putExtra("address"  , new String ("01234"));
      smsIntent.putExtra("sms_body"  , "Test ");
      
      try {
         startActivity(smsIntent);
         finish();
         Log.i("Finished sending SMS...", "");
      } catch (android.content.ActivityNotFoundException ex) {
         Toast.makeText(MainActivity.this, 
         "SMS faild, please try again later.", Toast.LENGTH_SHORT).show();
      }
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }
}

以下是 **res/layout/activity_main.xml** 檔案的內容:

這裡 abc 指的是 tutorialspoint 的 logo
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" 
   tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Drag and Drop Example"
      android:id="@+id/textView"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorials Point "
      android:id="@+id/textView2"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true"
      android:textSize="30dp"
      android:textColor="#ff14be3c" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_marginTop="48dp"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Compose SMS"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_marginTop="54dp"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />
      
</RelativeLayout>

以下是 **res/values/strings.xml** 的內容,用於定義兩個新的常量:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="app_name">tutorialspoint</string>
</resources>

以下是 **AndroidManifest.xml** 的預設內容:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.tutorialspoint" >
      
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.tutorialspoint.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

讓我們嘗試執行您的 **tutorialspoint** 應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟專案的某個活動檔案,然後單擊工具欄中的執行 Eclipse Run Icon 圖示。在啟動應用程式之前,Android Studio 將顯示以下視窗,以選擇您要執行 Android 應用程式的位置。

Android Mobile Device

選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示以下螢幕:

Android Mobile SMS Compose

現在,使用“撰寫簡訊”按鈕啟動 Android 內建的簡訊客戶端,如下所示:

Android Mobile SMS Screen

您可以修改任何給定的預設欄位,最後使用“傳送簡訊”按鈕將簡訊傳送到指定的收件人。

廣告