Broadcast Receiver as inner class in Android

An (non-static) inner class cannot be instantiated by Android via the AndroidManifest.xml (Android developer documentation on BroadcastReceiver):

You can either dynamically register an instance of this class with
Context.registerReceiver() or statically publish an implementation
through the tag in your AndroidManifest.xml.

So you can dynamically register the receiver. In my application I wanted to do the same for using Google’s Cloud to Device Messaging (C2DM) and my original AndroidManifest.xml contained:

<application...>
    <receiver android:name=".MyC2dmReceiver" android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.example.myapp" />
        </intent-filter>
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.example.myapp" />
        </intent-filter>
    </receiver>
</application>

I removed that receiver section and dynamically registered the receiver as follows:

public class AndroidService extends IntentService
{
    ... 
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.google.android.c2dm.intent.RECEIVE");
        filter.addAction("com.google.android.c2dm.intent.REGISTRATION");
        filter.addCategory("com.example.myapp");
        this.registerReceiver(new MyC2dmReceiver(), filter, "com.google.android.c2dm.permission.SEND", null);
        return super.onStartCommand(intent,flags,startId);
    }

    public class MyC2dmReceiver extends BroadcastReceiver
    {
        ...
    }
}

Leave a Comment