当前位置: 编程技术>移动开发
Android短信接收监听、自动回复短信操作例子
来源: 互联网 发布时间:2014-10-24
本文导语: 定义广播接收器的Action: 代码如下:private static final String TAG ="SmsService";/*** 信息发送状态广播*/private static final String ACTION_SMS_SEND = "com.SmsService.send"; /*** 信息接收状态广播*/private static final String ACTION_SMS_DELIVERY = "com.SmsService.deli...
定义广播接收器的Action:
代码如下:
private static final String TAG ="SmsService";
/**
* 信息发送状态广播
*/
private static final String ACTION_SMS_SEND = "com.SmsService.send";
/**
* 信息接收状态广播
*/
private static final String ACTION_SMS_DELIVERY = "com.SmsService.delivery";
/**
* 信息接收广播
*/
private static final String ACTION_SMS_RECEIVER = "android.provider.Telephony.SMS_RECEIVED";
定义并注册广播接收器,可以动态注册,也可以静态注册:
代码如下:
class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int resultCode = getResultCode();
if (intent.getAction().equals(ACTION_SMS_RECEIVER)){
Log.i(TAG, "SmsReceiver->onReceive");
SmsMessage sms = null;
Bundle bundle = intent.getExtras();//获取intent中的内容
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");//获取bundle里面的内容
for (Object obj : pdus) {
//下面两行将短信内容取出加入到message中
sms = SmsMessage.createFromPdu((byte[]) obj);
}
}
mHandler.obtainMessage(MSG_SMS_RECEIVE,sms).sendToTarget();
//接收信息发送状态
}else if (intent.getAction().equals(ACTION_SMS_SEND)){
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "短信发送成功");
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Log.i(TAG, "短信发送失败:GENERIC_FAILURE");
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Log.i(TAG, "短信发送失败:NO_SERVICE");
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Log.i(TAG, "短信发送失败:NULL_PDU");
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Log.i(TAG, "短信发送失败:RADIO_OFF");
break;
}
//接收信息接收状态
}else if (intent.getAction().equals(ACTION_SMS_DELIVERY)){
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "短信接收成功");
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Log.i(TAG, "短信接收失败:GENERIC_FAILURE");
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Log.i(TAG, "短信接收失败:NO_SERVICE");
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Log.i(TAG, "短信接收失败:NULL_PDU");
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Log.i(TAG, "短信接收失败:RADIO_OFF");
break;
}
}
}
}
这样就实现了短信自动回复功能,当然也可以实现接收到短信自动回拨电话。这里提供一个短信接收函数:
代码如下:
public void doReceiveSms(Intent intent) {
Object[] pdus = (Object[]) intent.getExtras().get("pdus");
SmsMessage [] messages = new SmsMessage[pdus.length];
for(int i=0; i= 70){
List list = smsManager.divideMessage(content);
for(String mMsg: list){
smsManager.sendTextMessage(phoneNumber, null, mMsg, null, null);
}
}else{
smsManager.sendTextMessage(phoneNumber, null, content, null, null);
}
}