Unable to instantiate a nested class (extends broadcastReceiver) when a Broadcast…

综合技术 2017-12-03 阅读原文

I am developing an application in Android and have an issue where Android framework throws java.lang.InstantiationException upon trying to instantiate a nested class. Here is the scenario.

  1. Class A extending Activity with nested class B which extends BroadcastReceiver:

    public class A extends Activity
        public void onCreate(){
        //Class B
        public class B extends BroadcastReceiver
            public void onReceive(...)
  2. Class declarations in manifest file : ....

Sorry for the bad indentation. Just couldn't find a way of properly indenting the code with so many tags.

  1. Broadcast from a service :
Intent updateIntent = new Intent();

With all the above given things, the code gets compiled, but when run on the device, after the broadcast is called, i get a InstantiationException saying cannot instantiate pacakage.A$B, and dalvik says no found.

Now this whole scenario works on Android 2.2, but somehow this fails on 2.1.

I don't know exactly what is happening. Am in need of help. Maybe something basic is missing by me.

Can anyone please help me? Thanks in advance.

Finally got a logical conclusion about the whole scenario myself. Was dumb enough not to read the

documentation on developer.android.net. It clearly stated that there are two way for an application to get the broadcast.

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.

I am using both the methods. My scenario should have failed on 2.2 as well, as those receivers were registered through manifest too and they should have been called automatically, but somehow it didn't ( This still remains a mystery ).

Removed all the receivers from manifest and just kept the dynamic registration of broadcast receivers and now the code works just like before only without the exceptions.

Thanks for all the help. 🙂

Hello, buddy!

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!


Android查缺补漏–BroadcastReceiver的类型与使用... Broadcast 是一种被用于应用内和应用之间传递信息的机制。一个广播可以对应多个接受者。一个完整的广播机制,需要具有以下三个要素: 发送广播的...
本地广播LocalBroadcastManager基本使用与源码解析... BroadcastReceiverBroadcastReceiver是Android四大组件之一,我们都比较熟悉,称它为“广播” ...
Obtaining BaseAdapter Data in the Service Class I have a BaseAdapter class using ViewHolders to display a list of checked apps. ...
BroadcastReceiver基础知识 什么是广播 在Android中,广播是一种广泛运用的在应用程序之间传输信息的机制,Android中我们要发送的广播内容是一个Intent,这个Intent中...
第十章 Service与BroadcastReceiver Service是Android四大组件中与Activity最相似的组件,他们都代表可执行的程序,Service与Activity的区别在于:Service一直在...