我使用Brodcast Receiver類來接收我的應用程序的短信。我也在清單文件中優先考慮我的申請。我在我的應用程序中編碼,如果短信是在一個特定的格式,那麼它應該加載第二個屏幕。它運行良好時,短信是特定的格式,但當我發送任何其他格式,因爲我的應用程序已被賦予更高的優先級,它首先接收短信(我的假設),然後它會生成強制關閉對話框,但消息顯示在通知欄中。只接收我的應用程序的特定格式的短信
我想要的是,如果短信是特定的格式,那麼它應該由我的應用程序處理,否則它應該由系統處理?
我的主要文件是:
package com.example.smsapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SMSApp extends BroadcastReceiver
{
@Override
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";
}
//---display the new SMS message---
//Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
String[] msgText;
msgText=str.split(",");
if(msgText[0].equals("second"))
{
Intent i = new Intent(context,Second.class);
i.putExtra("msg",msgText[1]);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
this.abortBroadcast();
}
}
清單文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.demo.smsapp" android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name="Second" class=".second"
android:label="SMSApp">
</activity>
<receiver android:name=".SMSApp">
<intent-filter android:priority="100">
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
</manifest>
第一個問題更換第二行被放入abortBroadcast中,如果塊,你開始一個新的活動,並發表您的logcat爲強制關閉 – ingsaurabh
感謝SAURABH爲回答。我已經把abortBroascast放在if塊中。我的Logcat顯示06-21 11:34:22.226:錯誤/ AndroidRuntime(452):導致:java.lang.ArrayIndexOutOfBoundsException 06-21 11:34:22.226:錯誤/ AndroidRuntime(452):在com.demo。 smsapp.SMSApp.onReceive(SMSApp.java:46) –