I would like to create a application that would respond to receiving SMS messages and display a dialog. How can I register the receiver in the manifest without defining within an activity?
I tried to keep the receiver/intent-filter tags in the manifest out of the activity tag but the emulator will not install the apk since there is no launch activity. Keeping the BroadcastReceiver as the main activity results in an "Unable to instantiate activity" error in the Logcat.
Any help?
Thanks, Sunny
Receiver class
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();
}
}
}
Manifest
<?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>
What you are trying to do is wrong for at least the following reasons...
In short, create a simple Activity which will appear in 'All apps' and has the MAIN/LAUNCHER intent settings and when it starts just have it create a dialog saying something like "Hi, welcome to ..." or some other feedback to the user letting them know that things have started correctly. Have an 'OK' button on the dialog which when pressed, calls the Activity's finish() method leaving the receiver in place.