我想創建一個應用程序來響應接收SMS消息並顯示對話框。我怎樣才能在清單中註冊接收者而無需在活動中定義?如何在沒有活動的情況下創建BroadcastReceiver
我試圖保持清單中的接收器/意圖過濾器標記出的活動代碼,但由於沒有發射活動的仿真器將無法安裝APK。將BroadcastReceiver作爲主要活動導致Logcat中的「無法實例化活動」錯誤。
任何幫助?
感謝, 陽光
Receiver類
public class SMSReceiver extends BroadcastReceiver {
// onCreat is invoked when an sms message is received.
// Message is attached to Intent via Bundle, stored in an Object
// array in the PDU format.
public void onReceive(Context context, Intent intent) {
// get the SMS message passed in from Bundle
Bundle bundle = intent.getExtras();
String bodyText = "";
String from = "";
if (bundle != null) {
//Retrieve sms message within Object array
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] msgs = new SmsMessage[pdus.length];
for (int i=0; i < msgs.length; i++)
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
for (SmsMessage message: msgs) {
bodyText = message.getMessageBody();
from = "Message from " + message.getOriginatingAddress() + ": ";
}
// Display message in pop up
Toast.makeText(context, from + bodyText, Toast.LENGTH_SHORT).show();
}
}
}
清單
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="home.splttingatms.SMSReceiver" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SMSReceiver"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SMSReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
</manifest>
我試圖做同樣的事情,其實更簡單,因爲所有我想要的是做的是讓在狀態欄上的通知時,我旋轉屏幕。模擬器上沒有這樣的運氣。 – 2012-02-09 00:26:51
看到我的答案在[創建廣播接收器沒有用戶界面](http://stackoverflow.com/questions/22318161/start-application-without-activity-my-broadcast-receiver-not-work/33249673#33249673) – 2015-10-21 01:55:23
看到我的回答於[創建沒有UI的廣播接收器](http://stackoverflow.com/questions/22318161/start-application-without-activity-my-broadcast-receiver-not-work/33249673#33249673) – 2015-10-21 02:09:17