Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách gửi SMS bằng SmsManager trên điện thoại Dual SIM Android

Giới thiệu

Ví dụ này minh họa cách gửi tin nhắn SMS sử dụng SmsManager trên Android, bao gồm xin quyền runtime và xử lý nhập liệu. Lưu ý: Android không cung cấp API công khai để chọn SIM cụ thể trên Dual SIM cho ứng dụng thường (chỉ system app). SmsManager.getDefault() sẽ dùng SIM mặc định của hệ thống.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="4dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editTextNum"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Nhập số điện thoại" />

    <EditText
        android:id="@+id/editTextMsg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Nhập nội dung tin nhắn" />

    <Button
        android:id="@+id/btnSendMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="SendSMS"
        android:text="Gửi tin nhắn" />

</LinearLayout>

Bước 3: Viết code logic (src/MainActivity.java)

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Button btnSend;
    EditText editTextNum, editTextMsg;
    private static final int PERMISSION_REQUEST = 101;

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

        editTextNum = findViewById(R.id.editTextNum);
        editTextMsg = findViewById(R.id.editTextMsg);
        btnSend = findViewById(R.id.btnSendMsg);
    }

    public void SendSMS(View view) {
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            MyMessage();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, PERMISSION_REQUEST);
        }
    }

    private void MyMessage() {
        String myNumber = editTextNum.getText().toString().trim();
        String myMsg = editTextMsg.getText().toString().trim();

        if (myNumber.isEmpty() || myMsg.isEmpty()) {
            Toast.makeText(this, "Không được để trống", Toast.LENGTH_SHORT).show();
        } else if (TextUtils.isDigitsOnly(myNumber)) {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(myNumber, null, myMsg, null, null);
            Toast.makeText(this, "Đã gửi tin nhắn", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Số điện thoại không hợp lệ", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                MyMessage();
            } else {
                Toast.makeText(this, "Cần quyền SEND_SMS để gửi tin nhắn", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Bước 4: Cấu hình Manifest (androidManifest.xml)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhập số điện thoại và nội dung, nhấn Gửi. App sẽ xin quyền lần đầu.

Cách gửi SMS bằng SmsManager trên điện thoại Dual SIM Android

Cách gửi SMS bằng SmsManager trên điện thoại Dual SIM Android

Cách gửi SMS bằng SmsManager trên điện thoại Dual SIM Android

Vấn đề Dual SIM

Android không cho phép ứng dụng thường chọn SIM slot (SIM 1 hoặc SIM 2) để gửi SMS. SmsManager.getDefault() luôn dùng SIM mặc định do người dùng thiết lập trong Cài đặt → Mạng & Internet → Thẻ SIM → Tin nhắn SMS.

Giải pháp thay thế

  • Dùng Intent.ACTION_SENDTO với URI smsto: để mở ứng dụng SMS mặc định, người dùng tự chọn SIM.
  • Ứng dụng hệ thống (system app) có thể dùng SubscriptionManager và SmsManager.createForSubscriptionId(subId) (API 22+).

Ví dụ dùng Intent (khuyến nghị cho Dual SIM)

Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
intent.putExtra("sms_body", message);
startActivity(intent);