android监听并获取短信

时间:2020-12-12 08:56:10
清单文件     <!--收短信的权限-->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <!--读取短信信息的权限-->
    <uses-permission android:name="android.permission.READ_SMS"/>
<receiver android:name=".business.common.SmsReceiver">
<intent-filter android:priority="1000"> <!--优先级:-1000~1000,系统短信优先级为-1-->
<!--订阅广播事件类型-->
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>


广播接收者

public class SmsReceiver extends BroadcastReceiver{
private static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//判断广播消息
if (action.equals(SMS_RECEIVED_ACTION)){
Bundle bundle = intent.getExtras();
//如果不为空
if (bundle!=null){
//将pdus里面的内容转化成Object[]数组
Object pdusData[] = (Object[]) bundle.get("pdus");// pdus :protocol data unit :
//解析短信
SmsMessage[] msg = new SmsMessage[pdusData.length];
for (int i = 0;i < msg.length;i++){
byte pdus[] = (byte[]) pdusData[i];
msg[i] = SmsMessage.createFromPdu(pdus);
}
StringBuffer content = new StringBuffer();//获取短信内容
StringBuffer phoneNumber = new StringBuffer();//获取地址
//分析短信具体参数
for (SmsMessage temp : msg){
content.append(temp.getMessageBody());
phoneNumber.append(temp.getOriginatingAddress());
}
EventBus.getDefault().post(new EventInfo(EventType.SMS_Receiver, "电话号码:"+phoneNumber.toString()+" 短信内容:"+content.toString()));
}
}
}
}

public class TestActivity extends Activity{
@InjectView(R.id.tv_content)
TextView tvContent;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
ButterKnife.inject(this);
}

public void onEventMainThread(EventInfo eventInfo) {
if (eventInfo.type == EventType.SMS_Receiver) {
tvContent.setText(eventInfo.obj+"..收到了");
}
}
}

activity_test.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="@dimen/space_50dp"
android:gravity="center"
android:text="测试页面"/>

<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@color/blue"/>
</LinearLayout>