我想创建一个应用程序来响应接收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