Android 下实现短信的收发
2010-03-04 05:14:00 来源:WEB开发网核心提示:发送短信相当的简单,只需要几行代码,Android 下实现短信的收发,如下:import android.telephony.gsm.SmsManager;import android.app.PendingIntent;......SmsManager sms = SmsManager.getDefault();Pe
发送短信相当的简单,只需要几行代码,如下:
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");
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");
[]
更多精彩
赞助商链接