对于我的项目,我需要使用 BroadcastReceiver 来接收 SMS。我的代码适用于我的模拟器,但不适用于我的手机。我的手机是 HTC one X (android 4.0.3)。在仿真中,当我收到短信时我可以看到吐司,而在我的手机中我看不到...
我的代码:
SMSReceiver.java:
package com.tuto.smsreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver
{
private final String ACTION_RECEIVE_SMS = "android.provider.Telephony.SMS_RECEIVED";
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(ACTION_RECEIVE_SMS))
{
Bundle bundle = intent.getExtras();
if (bundle != null)
{
Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } if (messages.length > -1)
{
final String messageBody = messages[0].getMessageBody();
final String phoneNumber = messages[0].getDisplayOriginatingAddress();
Toast.makeText(context, "Exp : " + phoneNumber, Toast.LENGTH_LONG).show();
Toast.makeText(context, "MSG recu : " + messageBody, Toast.LENGTH_LONG).show();
}
}
}
}
}
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tuto.smsreceiver"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver class="com.tuto.smsreceiver.SMSReceiver"
android:name="com.tuto.smsreceiver.SMSReceiver">
<intent-filter android:priority="999">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
</manifest>