[英]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.
其中之一应动态启动BroadcastReceiver-但它始终返回InstantiationException。 The BroadcastReceiver has a no-parameter constructor so it should work - but it doesn't.
BroadcastReceiver有一个无参数的构造函数,因此它应该可以工作-但事实并非如此。 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: 这是一个具有InnerClass BroadcastReceiver的活动,该活动尝试使用此便捷方法启动BroadcastReceiver:
// 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. 非常感谢您的帮助。
That is the problem 那就是问题所在
make you broadcast receiver a static inner class public static class MyBroadcastReceiver extends BroadcastReceiver 使您的广播接收器成为静态内部类公共静态类MyBroadcastReceiver扩展了BroadcastReceiver
or declare in its own file 或在自己的文件中声明
The no empty constructor messsage from the instantiation exception can be confusing 实例化异常中的无空构造函数消息可能会造成混淆
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.