我的应用程序的目的是获取一条短信,然后在对话框中的屏幕上显示它。它还应该使消息不会出现在电话收件箱中。目前我已经编写了我认为应该工作的代码,但是当我向手机发送文本时,它们只会出现在收件箱中,而应用程序根本没有任何响应。
下面的代码:
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
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]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
Intent act = new Intent(context, MainActivity.class);
act.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
act.putExtra("message",str);
context.startActivity(act);
//abortBroadcast();
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
显现:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cam.sms"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECIEVE_SMS"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.cam.sms.MainActivity"
android:label="@string/app_name"
android:alwaysRetainTaskState="True"
android:launchMode="singleInstance">"
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SettingsScreen"
android:alwaysRetainTaskState="True"
android:launchMode="singleInstance">
</activity>
<receiver android:name=".SMSReceiver" android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>