我确实有一个有很多静态方便方法的类。其中一个应该动态启动一个 BroadcastReceiver - 但它总是返回一个 InstantiationException。BroadcastReceiver 有一个无参数的构造函数,所以它应该可以工作——但它没有。这是我到目前为止所做的:
这是其类中的便捷方法:
// 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 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() {
// ...
}
}
这种方法有什么问题?
非常感谢任何帮助。