界面效果
布局文件
<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"
tools:context="com.xsism.smssender.MainActivity"
android:orientation="vertical"
>
<EditText
android:id="@+id/phoneNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入接收方号码"
android:inputType="phone"
/>
<EditText
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="top"
android:hint="请输入短信内容"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点我发送短信"
android:onClick="sendSMSBtnClicked"
/>
</LinearLayout>
权限清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xsism.smssender"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<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=".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>
实现代码
package com.xsism.smssender;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.telephony.SmsManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendSMSBtnClicked(View btn){
System.out.println("点击了发送按钮");
EditText et_phoneNo = (EditText)findViewById(R.id.phoneNo);
String phoneNo = et_phoneNo.getText().toString();
EditText et_content = (EditText)findViewById(R.id.content);
String content = et_content.getText().toString();
// 获取默认的短信管理器
SmsManager manager = SmsManager.getDefault();
// 分割
ArrayList<String> contentArr = manager.divideMessage(content);
for (String string : contentArr) {
// 第2个参数使用默认的短信中心值
// 第4个参数是发送成功与否的广播(以后会学)
// 第5个参数是对方成功接收与否的广播(以后会学)
// 此处应该要权限
manager.sendTextMessage(phoneNo, null, string, null, null);
}
}
}