需求:在文本框中分别键入短信地址和内容,点击发送按钮发送短信
layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.android.mrseng.msgsender.MainActivity">
<EditText
android:id="@+id/editText_phoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入电话号码"
android:inputType="phone"
/>
<EditText
android:id="@+id/editText_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="5"
android:hint="请键入短信内容"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="发送"
android:onClick="sendMsg"
/>
</LinearLayout>
activity:
package com.android.mrseng.msgsender;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.EditText;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 按钮点击事件
*
* @param v
*/
public void sendMsg(View v) {
//获取短信发送的内容和目的号码
String phoneNumber = ((EditText) findViewById(R.id.editText_phoneNumber)).getText().toString();
String content = ((EditText) findViewById(R.id.editText_content)).getText().toString();
//发短信
SmsManager smsManager = SmsManager.getDefault();
//对长短信分割
ArrayList<String> contents = smsManager.divideMessage(content);
for (String c : contents) {
/*
* 参数:目标地址,短信中心地址(null为默认),短信内容,发送失败的广播,发送成功的广播
*/
smsManager.sendTextMessage(phoneNumber, null, c, null, null);
}
}
}
//直接运行会报错:Sending SMS message: uid 10060 does not have android.permission.SEND_SMS.
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.mrseng.msgsender">
<!--声明发送短信的权限-->
<uses-permission android:name="android.permission.SEND_SMS"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
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>