我有有很多的静态便捷方法的类。 其中一人应动态地启动一个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() {
// ...
}
}
有什么不对这种做法?
任何帮助,高度赞赏。