发送短信相当的简单,只需要几行代码,如下:
import android.telephony.gsm.SmsManager;
import android.app.PendingIntent;
......
SmsManager sms = SmsManager.getDefault();
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
sms.sendTextMessage(phoneNumber, null, MsgStr, pi, null);
其中参数phoneNumber和MsgStr均是String类型,表示接收方的电话号码和短信内容
接收短信相对而言麻烦一些,需要使用全局的接收类BroadcastReceiver,完整代码如下:
package com.hello.db;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
public class MessageDemo extends BroadcastReceiver {
private static final String strACT = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(strACT)) {
StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] msg = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
for (SmsMessage currMsg : msg) {
sb.append("From:");
sb.append(currMsg.getDisplayOriginatingAddress());
sb.append("\nMessage:");
sb.append(currMsg.getDisplayMessageBody());
}
}
Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
Intent i = new Intent(context, DBDemo.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
此处的接收是收到消息时,弹出一个Toast提示,在此基础上稍做修改也可以实现将收到的消息放入文本框从而展示出来。注意最后必须将控制权交还给上一个Activity,不然程序会出错。
好了,收发短信的代码都有了,下面需要配置权限,只有程序拥有了权限,这些功能才能真正被使用
修改AndroidManifest.xml,在Activity下添加receiver节点:
<receiver android:name="MessageDemo">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
随后在application下添加节点:
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>