当广播接收器使用InstantiationException的newInstance(Instant

2019-10-17 05:30发布

我有有很多的静态便捷方法的类。 其中一人应动态地启动一个BroadcastReceiver - 但它总是返回InstantiationException。 该广播接收器有一个无参数的构造函数,因此它应该工作 - 但事实并非如此。 这是我做了到目前为止:

下面是它的类的简便方法:

// 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;
    }

    // ...
}

下面是与广播接收器将InnerClass试图启动与此便捷方法的广播接收器的活动:

// 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() {
        // ...
    }
}

有什么不对这种做法?

任何帮助,高度赞赏。

Answer 1:

那就是问题所在

让你广播接收机静态内部类的公共静态类MyBroadcastReceiver扩展广播接收器

或者在它自己的文件中声明

从实例异常没有空的构造消息话题可能会造成混淆



文章来源: InstantiationException when using newInstance on BroadcastReceiver