我正在编写一个广播侦听器来监听SMS_RECEIVED动作。如果我动态注册它,它可以正常工作但是如果我在Manifest文件中静态注册它,则不会调用广播接收器。
<receiver android:name=".MyReceiverBroadcast"><intent-filter>
<action android:name="android.provider.Telephony.SMS_RECIEVED"></action>
</intent-filter></receiver>
我的广播接收器如下
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(action.equals(SMS_RECEIVED_ACTION))
{
Log.v("sms", "reciever called");
Object[] messages=(Object[])intent.getExtras().get("pdus");
for(Object message:messages)
{
byte[] messagedata=(byte[])message;
SmsMessage smsmessage=SmsMessage.createFromPdu(messagedata);
processmessage(smsmessage,context);
}
}
}
private void processmessage(SmsMessage smsmessage,Context c) {
String from=smsmessage.getOriginatingAddress();
String messcontent=smsmessage.getMessageBody();
Toast.makeText(c,"from ="+from+" and mess="+messcontent,Toast.LENGTH_LONG).show();
Log.v("sms","from ="+from+" and mess="+messcontent);
}
我的清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tech.myfirst" >
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>
<activity
android:name=".SmsReceiverDemo"
android:label="SmsReciever Demo"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.example.tech.myfirst.MyReceiverBroadcast"><intent-filter>
<action android:name="android.provider.Telephony.SMS_RECIEVED"></action>
</intent-filter></receiver>
</application>
</manifest>
我已添加了所有必要的权限。 我在这里失踪了什么。 我在模拟器nexus 5 api 21上运行程序。 感谢
答案 0 :(得分:1)
假设其他一切都是正确的,则问题是您在RECEIVED
的{{1}}中为清单中的<intent-filter>
条目拼错了<action>
。它应该是:
<receiver>
您可能还想检查<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
字符串的值。
答案 1 :(得分:0)
之前我遇到过这个问题,并通过更改属性
解决了这个问题android:name=".MyReceiverBroadcast"
要
android:name="my.package.name.MyReceiverBroadcast"
我不知道为什么会这样,但它对我有用。