开发者

Unable to instantiate a nested class ( extends broadcastReceiver ) when a sendBroadcast is made

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();
    updateIntent.setAction("desired_action");
    sendBroadcast(accountPropertyUpdateIntent开发者_如何学编程);

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 <receiver> 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. :)


Nested class documentation says (last paragraph):

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();

So Android can not instantiate inner class automatically. Just move class B to top-level (into separate file B.java).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜