Welcome 微信登录

首页 / 移动开发 / Android / Android开发中实现发送短信的小程序示例

2016412151249217.gif (248×371)
上图为代码结构图。
现在我们看下具体的代码。
Send.java
package cn.com.sms.send;import java.util.ArrayList; import java.util.Iterator;import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;public class Send extends Activity { private String message; private String number ; private EditText editText; private EditText editText2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);editText = (EditText) this.findViewById(R.id.number);editText2 = (EditText)this.findViewById(R.id.message);Button button = (Button)this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {number = editText.getText().toString();message = editText2.getText().toString();// 在LogCat中可以查看到number和message的相关信息Log.i("number", number);Log.i("message", message);/*获取系统默认的信息管理器,一定要注意的是SmsManager是android.telephony.SmsManager;这和*我们使用的版本有关,在 Android 2.0 以前 应该使用 android.telephony.gsm.SmsManager*Android 2.0 之后的版本应该用 android.telephony.SmsManager。*/ SmsManager smsManager = SmsManager.getDefault(); /*PendingIntent.getBroadcast返回一个用于广播的PendingIntent对象,类似于调用Content.sendBroadcast();*/ PendingIntent paIntent = PendingIntent.getBroadcast(Send.this, 0, new Intent("SMS_SENT"), 0); PendingIntent deliveryIntent = PendingIntent.getBroadcast(Send.this, 0, new Intent("SMS_DELIVERED"), 0); // smsManager.divideMessage有些时候短信如果超过了字数,我们就需要这个方法来帮我们拆分短信内容。 ArrayList<String> smses = smsManager.divideMessage(message); Iterator<String> iterator = smses.iterator(); while(iterator.hasNext()){ String temp = iterator.next(); //发送短信 smsManager.sendTextMessage(number, null, temp, paIntent, deliveryIntent); } // 弹出一个浮动框显示提示内容,Toast.LENGTH_LONG代表浮动框显示时间的长短 Toast.makeText(Send.this, "短信发送完成", Toast.LENGTH_LONG).show(); } });} } 
 main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="欢迎使用短信发送器,请输入电话号码" /><EditText android:id="@+id/number" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="这里输入电话号码"/><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="欢迎使用短信发送器,请输入短信内容"/><EditText android:id="@+id/message" android:layout_width="fill_parent" android:layout_height="wrap_content" android:minLines="3" android:hint="这里输入短信内容"/><Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="send"/> </LinearLayout> 
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"package="cn.com.sms.send"android:versionCode="1"android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <uses-permission android:name="android.permission.SEND_SMS"></uses-permission><application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Send"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> 
最终效果图为:

2016412151344499.gif (369×405)
和打电话小程序一样,这里也需要开启两个AVD才能进行功能测试。

碎碎念:
发短信应用的主要的类就是SmsManager。 在 Android 2.0 以前 应该使用 android.telephony.gsm.SmsManager
之后应该用 android.telephony.SmsManager;
SmsManager smsManager = SmsManager.getDefault();
意思为获取系统默认的信息管理器

smsManager.sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent)
             -- destinationAddress:目标电话号码
             -- scAddress:服务商的短信中心号码(例如中国移动的短信中心号码),测试可以不填。
             -- text: 短信内容
             -- sentIntent:发送 -->中国移动 --> 中国移动发送失败 --> 返回发送成功或失败信号 --> 后续处理   即,这个意图包装了短信发送状态的信息
             -- deliveryIntent: 发送 -->中国移动 --> 中国移动发送成功 --> 返回对方是否收到这个信息 --> 后续处理  即:这个意图包装了短信是否被对方收到的状态信息(供应商已经发送成功,但是对方没有收到)。

public static PendingIntent getBroadcast (Context context, int requestCode, Intent intent, int flags)
返回一个用于广播的PendingIntent,类似于调用Context.sendBroadcast()函数
requestCode 暂时不用
intent 是用于广播的intent
flag 有:FLAG_ONE_SHOT, FLAG_NO_CREATE, FLAG_CANCEL_CURRENT, FLAG_UPDATE_CURRENT 用于设置新建的PendingIntent是使用一次、如无则不创建、取消当前、更新当前等属性。
此外,我们还要在AndroidManifest.xml中声明短信发送权限。
 <uses-permission android:name="android.permission.SEND_SMS"/>
有的时候,我们两个AVD进行模拟发短信时,会发现有时候该程序无法正常使用。系统会提示我们NO DNS servers found,找不到DNS服务。这种情况一般是由于你的电脑没有联入网络的原因造成的。
发送短信:   

SmsManager smsMgr = SmsManager.getDefault();smsMgr.sendTextMessage(address, null, message, null, null);
 
显示写短信界面:   

Uri smsToUri = Uri.parse("smsto://10086");Intent mIntent = new Intent( android.content.Intent.ACTION_SENDTO, smsToUri );startActivity( mIntent );
 
发送电子邮件:  

Intent i = new Intent(Intent.ACTION_SEND);i.putExtra(Intent.EXTRA_EMAIL, address);i.putExtra(Intent.EXTRA_SUBJECT, filename);i.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filename)); ;i.setType("text/csv");startActivity(Intent.createChooser(i, "EMail File"));
升级版:
该代码为其添加了广播接收者的监听。详细代码如下

package cn.com.sms.send;import java.util.ArrayList; import java.util.Iterator;import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;public class Send extends Activity { private String message; private String number ; private EditText editText; private EditText editText2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);editText = (EditText) this.findViewById(R.id.number);editText2 = (EditText)this.findViewById(R.id.message);Button button = (Button)this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {number = editText.getText().toString();message = editText2.getText().toString();// 在LogCat中可以查看到number和message的相关信息Log.i("number", number);Log.i("message", message);/*获取系统默认的信息管理器,一定要注意的是SmsManager是android.telephony.SmsManager;这和*我们使用的版本有关,在 Android 2.0 以前 应该使用 android.telephony.gsm.SmsManager*Android 2.0 之后的版本应该用 android.telephony.SmsManager。*/ SmsManager smsManager = SmsManager.getDefault(); /*PendingIntent.getBroadcast返回一个用于广播的PendingIntent对象,类似于调用Content.sendBroadcast();*/ PendingIntent paIntent = PendingIntent.getBroadcast(Send.this, 0, new Intent("SMS_SENT2"), 0); PendingIntent deliveryIntent = PendingIntent.getBroadcast(Send.this, 0, new Intent("SMS_DELIVERED2"), 0);// 注册一个BroadcastReceiver,当有匹配它的IntentFilter的Intent出现时,该方法会被触发 registerReceiver(new BroadcastReceiver(){@Override public void onReceive(Context context, Intent intent) { int resultCode = getResultCode(); switch(resultCode){ case Activity.RESULT_OK: Toast.makeText(getBaseContext(), "信息发送成功了哦、", Toast.LENGTH_LONG).show(); break; default: Toast.makeText(getBaseContext(), "信息发送失败了哦、", Toast.LENGTH_LONG).show();} } }, new IntentFilter("SMS_SENT2")); registerReceiver(new BroadcastReceiver() {@Override public void onReceive(Context context, Intent intent) { Toast.makeText(getBaseContext(), "deliveryIntent", Toast.LENGTH_LONG).show(); Log.i("短信接收人是否查看信息", "看了"); } }, new IntentFilter("SMS_DELIVERED2"));// smsManager.divideMessage有些时候短信如果超过了字数,我们就需要这个方法来帮我们拆分短信内容。 ArrayList<String> smses = smsManager.divideMessage(message); Iterator<String> iterator = smses.iterator(); while(iterator.hasNext()){ String temp = iterator.next(); //发送短信 smsManager.sendTextMessage(number, null, temp, paIntent, deliveryIntent); } // 弹出一个浮动框显示提示内容,Toast.LENGTH_LONG代表浮动框显示时间的长短 Toast.makeText(Send.this, "短信发送完成", Toast.LENGTH_LONG).show(); } });} } 
main.xml与AndroidManifest.xml和前面的代码一样。
registerReceiver()用于注册广播接受者。该方法在Content中这样定义的。
public abstract Intent registerReceiver(BroadcastReceiver receiver,IntentFilter filter);系统如果查询到满足filter的广播,便会教给receiver,让其处理。一般都是在其onReceive()方法中处理。
如果不是在代码中主动通过registerReceiver()进行注册,那么就要从AndroidManifest.xml进行配置,代码如下
<receiver android:name="类名"> <intent-filter> <action android:name="接收者中Intent参数的action属性" /> </intent-filter> </receiver>
这里需要注意,在配置文件中activity标签和receiver标签是平级的。
在模拟器中发送中文会接收方出现乱码的问题,但是在真机中,就不会出现乱码的情况了。所以开发者只需要正常开发短信功能,不需要编码转换。