如何在 Android 中以程式設計方式讀取裝置上的簡訊?
簡介
在 Android 應用程式中,我們經常看到應用程式讀取使用者手機上的簡訊並在應用程式內顯示。例如,當我們建立簡訊應用程式時,我們會將使用者手機上的簡訊顯示在我們的應用程式中。在本文中,我們將探討如何在 Android 中以程式設計方式讀取裝置上的簡訊。
實現
我們將建立一個簡單的應用程式,其中我們將建立一個 TextView 用於顯示應用程式標題。然後,我們將建立另外三個 TextView,分別用於顯示發件人姓名、簡訊正文以及接收簡訊的日期。在我們的應用程式中,我們將顯示收件箱中最近收到的簡訊。現在讓我們轉到 Android Studio 建立一個新專案。
步驟 1:在 Android Studio 中建立一個新專案
導航到 Android Studio,如下面的螢幕所示。在下面的螢幕中,點選“新建專案”以建立一個新的 Android Studio 專案。

點選“新建專案”後,您將看到下面的螢幕。

在這個螢幕中,我們只需選擇“空活動”並點選“下一步”。點選“下一步”後,您將看到下面的螢幕。

在這個螢幕中,我們只需指定專案名稱。然後包名將自動生成。
注意:確保選擇語言為 Java。
指定所有詳細資訊後,點選“完成”以建立一個新的 Android Studio 專案。
專案建立完成後,我們將看到兩個開啟的檔案,即 activity_main.xml 和 MainActivity.java 檔案。
步驟 2:使用 activity_main.xml
導航到 activity_main.xml。如果此檔案不可見,要開啟此檔案,在左側窗格中導航到 app > res > layout > activity_main.xml 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- text view to displaying heading of application --> <TextView android:id="@+id/idTVHeading" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:text="Read SMS in Android" android:textAlignment="center" android:textColor="@color/black" android:textSize="20sp" android:textStyle="bold" /> <!-- on below line creating a text view for displaying the sms header --> <TextView android:id="@+id/idTVNumber" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVHeading" android:layout_centerHorizontal="true" android:layout_margin="10dp" android:padding="4dp" android:text="NUmber" android:textAlignment="center" android:textColor="@color/black" android:textSize="18sp" /> <!-- on below line creating a text view for displaying the sms body --> <TextView android:id="@+id/idTVSMSBody" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVNumber" android:layout_centerHorizontal="true" android:layout_margin="10dp" android:padding="4dp" android:text="SMS Body" android:textAlignment="center" android:textColor="@color/black" android:textSize="18sp" /> <!-- on below line creating a text view for displaying the date on which sms have recieved. --> <TextView android:id="@+id/idTVSMSDate" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVSMSBody" android:layout_centerHorizontal="true" android:layout_margin="10dp" android:padding="4dp" android:text="SMS Date" android:textAlignment="center" android:textColor="@color/black" android:textSize="18sp" /> </RelativeLayout>
說明:在上面的程式碼中,我們建立一個根佈局作為相對佈局。在此佈局內,我們建立一個 TextView 用於顯示應用程式標題。然後,我們建立另外三個 TextView,第一個 TextView 顯示發件人姓名,第二個 TextView 顯示發件人的簡訊正文,第三個 TextView 顯示接收簡訊的日期。
步驟 3:在 AndroidManifest.xml 檔案中新增許可權
導航到 app > AndroidManifest.xml 檔案,並在 manifest 標籤中新增以下許可權以讀取簡訊。
<uses-permission android:name="android.permission.READ_SMS" />
步驟 4:使用 MainActivity.java 檔案
導航到 MainActivity.java。如果此檔案不可見,要開啟此檔案,在左側窗格中導航到 app > res > layout > MainActivity.java 以開啟此檔案。開啟此檔案後,將以下程式碼新增到其中。程式碼中添加了註釋以詳細瞭解。
package com.example.java_test_application; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Intent; import android.content.IntentSender; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.Telephony; import android.text.TextUtils; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.credentials.Credential; import com.google.android.gms.auth.api.credentials.CredentialPickerConfig; import com.google.android.gms.auth.api.credentials.CredentialRequest; import com.google.android.gms.auth.api.credentials.CredentialRequestResult; import com.google.android.gms.auth.api.credentials.Credentials; import com.google.android.gms.auth.api.credentials.CredentialsClient; import com.google.android.gms.auth.api.credentials.CredentialsOptions; import com.google.android.gms.auth.api.credentials.HintRequest; import com.google.android.gms.auth.api.credentials.IdentityProviders; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResolvableApiException; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import org.w3c.dom.Text; import java.util.Date; public class MainActivity extends AppCompatActivity { // creating variables for text view on below line for displaying sender name, body of the message and the date on which message is received. private TextView numberTV, bodyTV, dateTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing variables for text view on below line. numberTV = findViewById(R.id.idTVNumber); bodyTV = findViewById(R.id.idTVSMSBody); dateTV = findViewById(R.id.idTVSMSDate); // creating a variable for content resolver on below line. ContentResolver cr = getApplicationContext().getContentResolver(); // creating a variable for cursor on below line and setting uri as sms uri. Cursor c = cr.query(Telephony.Sms.CONTENT_URI, null, null, null, null); // on below line checking if the cursor is not null. if (c != null) { // on below line moving to the first position. if (c.moveToFirst()) { // on below line extracting the sms data from the cursor. String smsDate = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.DATE)); // on below line extracting the sender name/ number from cursor. . String number = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.ADDRESS)); // on below line extracting the body of the sms from the cursor. String body = c.getString(c.getColumnIndexOrThrow(Telephony.Sms.BODY)); // on below line converting date in date format. Date dateFormat = new Date(Long.valueOf(smsDate)); // on below line moving cursor to next position. c.moveToNext(); // on below line setting data from the string to our text views. numberTV.setText("Sender is : " + number); bodyTV.setText("Body is :
" + body); dateTV.setText(dateFormat.toString()); } // on below line closing the cursor. c.close(); } else { // on below line displaying toast message if there is no sms present in the device. Toast.makeText(this, "No message to show!", Toast.LENGTH_SHORT).show(); } } }
說明:在上面的程式碼中,首先我們為 TextView 建立變數。現在我們將看到 onCreate 方法。這是每個 Android 應用程式的預設方法。當應用程式檢視建立時,將呼叫此方法。在此方法內,我們設定內容檢視,即名為 activity_main.xml 的佈局檔案,以從該檔案設定 UI。在 onCreate 方法內,我們使用我們在 activity_main.xml 檔案中給出的 id 初始化 button 變數。然後,我們為內容解析器建立一個變數。然後,我們建立並初始化遊標變數,方法是將簡訊查詢和其他引數作為 null 傳遞。然後,我們檢查遊標是否不為 null。在這種情況下,我們將遊標移動到第一個位置。在此方法內,我們提取簡訊的不同部分,例如發件人姓名、簡訊正文以及接收簡訊的日期。獲取所有資料後,我們將這些資料設定為我們建立的 TextView。然後,我們關閉遊標。如果遊標為 null,這意味著收件箱為空,在這種情況下,我們將顯示一條吐司訊息,提示“沒有簡訊顯示”。
新增上述程式碼後,我們只需點選頂部欄中的綠色圖示即可在移動裝置上執行我們的應用程式。
注意 - 確保您已連線到您的真實裝置或模擬器。
輸出

結論
在本文中,我們瞭解瞭如何在 Android 中以程式設計方式讀取裝置上的簡訊。