首页  编辑  

安卓4.4以下版本短信接收和监听

Tags: /Android/   Date Created:
首先创建一个SMSReceiver.java文件:
package com.zhjinrui.batcom;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;

public class SMSReceiver extends BroadcastReceiver {
final String TAG = "blabla";

public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String address = messages[i].getOriginatingAddress();
String body = messages[i].getDisplayMessageBody();
Log.i(TAG, "收到短信: " + address + "=>" + body);
}
}
}
然后在AndroidManifest.xml中,添加用户权限和receiver即可:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<receiver android:name=".SMSReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>