无法在sendBroadcast实例化嵌套类(扩展broadcastReceiver)
问题描述:
我正在Android中开发应用程序,并遇到Android框架在试图实例化嵌套类时抛出java.lang.InstantiationException的问题。 这是场景。无法在sendBroadcast实例化嵌套类(扩展broadcastReceiver)
public class A extends Activity
{
public void onCreate(){
....};
//Class B
public class B extends BroadcastReceiver
{
public void onReceive(...)
}
}
类声明中的清单文件: ....
类A延伸活动
对不起,缩进。只是找不到用这么多标签正确缩进代码的方法。
- 广播从服务:
Intent updateIntent = new Intent();
updateIntent.setAction("desired_action");
sendBroadcast(accountPropertyUpdateIntent);
与所有上面给出的东西,代码被编译,但在设备上运行,广播被称为后,我得到一个InstantiationException说不能实例化pacakage.A $ B,并且dalvik说没有找到。
现在这整个场景在Android 2.2上工作,但不知何故这在2.1上失败。
我不知道到底发生了什么。我需要帮助。也许一些基本的东西是我失踪的。
任何人都可以帮我吗?提前致谢。
答
最后我自己对整个场景做了一个逻辑结论。足够愚蠢的是不读取developer.android.net上的<receiver>
文档。它清楚地表明,应用程序获得广播的方式有两种。
There are two ways to make a broadcast receiver known to the system:
One is declare it in the manifest file with this element.
The other is to create the receiver dynamically in code and register it with the
Context.registerReceiver() method.
See the BroadcastReceiver class description for more on dynamically created receivers.
我正在使用这两种方法。 我的场景在2.2上也应该失败,因为那些接收器也是通过manifest来注册的,它们应该是自动调用的,但不知何故它不会(这仍然是个谜)。
从清单中删除了所有接收者,并保持广播接收者的动态注册,现在代码与以前一样工作,只是没有例外。
感谢您的帮助。 :)
答
Nested class documentation说(最后一段):
To instantiate an inner class, you must first instantiate the outer class.
Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
因此Android无法自动实例化内部类。只需将类B
移动到顶层(分开的文件B.java
)。
我敢肯定,你不能有一个嵌套的broadcastreciever类。你为什么要这样做? – Falmarri 2010-11-24 16:40:35
需要A类内的broadcastreceiver,以便在某些广播事件中,B类可以直接访问A类的成员并相应地更新UI。 – Puneet 2010-11-25 03:11:03