您好我已经实现了BroadcastReceiver,就像在这篇文章中一样 Android – Listen For Incoming SMS Messages
但出于某种原因,当我尝试通过应用程序运行从一个AVD向第二个AVD发送消息时,它甚至不打印"收到的消息"要记录的文字。
清单:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application>
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SmsListener">
<intent-filter android:priority="2147483647">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
广播接收器
public class SmsListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("SmsListener", "Message received");
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Log.d("SmsListener", "Message received");
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null){
//---retrieve the SMS message received---
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
Log.d("SmsListener", "Message: "+msgBody);
}
} catch(Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
}
}
}
谁能解释问题出在哪里?
答案 0 :(得分:0)
从KitKat传入的短信广播拦截开始有点改变。查看此清单,其中包括Kitkat和Kitkat之前的版本:
<!-- SMS receiver -->
<receiver
android:name=".SmsReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.BROADCAST_SMS" >
<intent-filter android:priority="2147483647" > <!-- 999 is highest system priority, so it's hack 2147483647 -->
<action android:name="android.provider.Telephony.SMS_RECEIVED" /> <!-- pre kitkat action -->
<action android:name="android.provider.Telephony.SMS_DELIVER" /> <!-- kitkat action -->
</intent-filter>
</receiver>
因此,根据Android版本,您必须以不同方式拦截:
@Override
public void onReceive(Context context, Intent intent) {
//<action android:name="android.provider.Telephony.SMS_RECEIVED" /> <!-- pre kitkat action -->
//<action android:name="android.provider.Telephony.SMS_DELIVER" /> <!-- kitkat action -->
//if it is kitkat - ignore pre kitkat action
if(intent.getAction().equalsIgnoreCase("android.provider.Telephony.SMS_RECEIVED") && android.os.Build.VERSION.SDK_INT >= 19)
return;
//if it is not kitkat - ignore kitkat action
if(intent.getAction().equalsIgnoreCase("android.provider.Telephony.SMS_DELIVER") && android.os.Build.VERSION.SDK_INT < 19)
return;
//blah-blah
}