版面配置 (activity_main.xml)
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp" >
<TextView android:id="@+id/phone_lable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="收件號碼" />
<EditText android:id="@+id/edit_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/phone_lable"
android:inputType="phone"
android:ems="10" />
<TextView android:id="@+id/sms_lable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/edit_phone"
android:layout_marginTop="22dp"
android:text="簡訊內容" />
<EditText android:id="@+id/edit_sms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/But_sms"
android:layout_alignLeft="@id/sms_lable"
android:ems="10"
android:inputType="textMultiLine" />
<Button android:id="@+id/But_sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="14dp"
android:text="發送簡訊" />
</RelativeLayout>
權限宣告 (AndroidManifest.xml)
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" /> <!-- 部分裝置需要 -->
核心邏輯 (SmsActivity.java)
public class SmsActivity extends Activity {
private Button btnSend;
private EditText etPhone, etContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
btnSend = findViewById(R.id.But_sms);
etPhone = findViewById(R.id.edit_phone);
etContent = findViewById(R.id.edit_sms);
btnSend.setOnClickListener(v -> sendSms());
}
/** 發送簡訊 (支援長簡訊自動分段) */
private void sendSms() {
String phone = etPhone.getText().toString().trim();
String text = etContent.getText().toString().trim();
if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(text)) return;
SmsManager smsManager = SmsManager.getDefault();
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(), PendingIntent.FLAG_IMMUTABLE);
// 長簡訊自動分段
ArrayList parts = smsManager.divideMessage(text);
for (String part : parts) {
smsManager.sendTextMessage(phone, null, part, sentPI, null);
}
Toast.makeText(this, "簡訊已發送", Toast.LENGTH_LONG).show();
}
/** 發送彩訊 (MMS) - 呼叫系統介面 */
private void sendMms() {
String phone = etPhone.getText().toString().trim();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("address", phone);
intent.putExtra("sms_body", "彩訊內容");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/a.jpg")); // 附件
intent.setType("image/jpeg");
startActivity(intent); // 彈出系統編輯介面
}
}
重點說明
- SMS:直接由
SmsManager 背景發送,需 SEND_SMS 權限。
- MMS:透過
Intent.ACTION_SEND 唤起系統編輯器,使用者確認後發送,不需特殊權限。
- Android 4.4+ 預設簡訊 App 機制下,非預設 App 發送 SMS 可能受限,建議引導使用者設為預設或改用 Intent。