Search code examples
javaandroidbroadcastreceiverinstantiation

InstantiationException when using newInstance on BroadcastReceiver


I do have a class with lots of static convenience methods. One of them should start a BroadcastReceiver dynamically - but it always returns an InstantiationException. The BroadcastReceiver has a no-parameter constructor so it should work - but it doesn't. Here's what I did so far:

Here's the convenience method in it's class:

// Static convenience methods in a tools class
public class MyTools {

    // Start BroadcastReceiver dynamically
    public static BroadcastReceiver startBroadcastReceiver(Context context,
            Class<? extends BroadcastReceiver> receiverClass, String receiverTag) {

        BroadcastReceiver receiver = null;

        try {
            receiver = (BroadcastReceiver) receiverClass.newInstance();
            if (receiver != null) {
                IntentFilter intentFilter = new IntentFilter(receiverTag);
                if (intentFilter != null) {
                    context.registerReceiver(receiver, intentFilter);
                }
            }
        } catch (Exception exception) {
            // --> InstantiationException
        }

        return receiver;
    }

    // ...
}

Here's an activity with an InnerClass BroadcastReceiver that tries to start the BroadcastReceiver with this convenience method:

// An activity with an InnerClass BroadcastReceiver
public class MyActivity extends Activity {

    public class MyBroadcastReceiver extends BroadcastReceiver {

        public static final String TAG = "aa.bb.cc.MyActivity.MyBroadcastReceiver";

        public static final long ACTION_UNDEFINED = 0;
        public static final long ACTION_DOSOMETHING = 1;

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                Bundle bundleExtras = intent.getExtras();
                if (bundleExtras != null) {
                    long action = bundleExtras.getLong("ACTION");
                    if (action == ACTION_DOSOMETHING) {
                        doSomething();
                    }
                }
            }
        }
    }

    private MyBroadcastReceiver receiver;

    @Override
    protected void onResume() {
        super.onResume();

        // Start BroadcastReceiver
        receiver = (MyBroadcastReceiver) MyTools.startBroadcastReceiver(this,
                MyBroadcastReceiver.class, MyBroadcastReceiver.TAG);
    }


    public void doSomething() {
        // ...
    }
}

What's wrong with this approach?

Any help is highly appreciated.


Solution

  • That is the problem

    make you broadcast receiver a static inner class public static class MyBroadcastReceiver extends BroadcastReceiver

    or declare in its own file

    The no empty constructor messsage from the instantiation exception can be confusing