2010-11-24 54 views
4

我正在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(...) 
    } 
} 
  • 類聲明中的清單文件: ....

  • 與延伸的BroadcastReceiver嵌套類乙

    1. 類A延伸活動

    對不起,縮進。只是找不到用這麼多標籤正確縮進代碼的方法。

    1. 廣播從服務:
    
        Intent updateIntent = new Intent(); 
        updateIntent.setAction("desired_action"); 
        sendBroadcast(accountPropertyUpdateIntent); 
    

    與所有上面給出的東西,代碼被編譯,但在設備上運行,廣播被稱爲後,我得到一個InstantiationException說不能實例化pacakage.A $ B,並且dalvik說沒有找到。

    現在這整個場景在Android 2.2上工作,但不知何故這在2.1上失敗。

    我不知道到底發生了什麼。我需要幫助。也許一些基本的東西是我失蹤的。

    任何人都可以幫我嗎?提前致謝。

    +0

    我敢肯定,你不能有一個嵌套的broadcastreciever類。你爲什麼要這樣做? – Falmarri 2010-11-24 16:40:35

    +0

    需要A類內的broadcastreceiver,以便在某些廣播事件中,B類可以直接訪問A類的成員並相應地更新UI。 – Puneet 2010-11-25 03:11:03

    回答

    4

    最後我自己對整個場景做了一個邏輯結論。足夠愚蠢的是不讀取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來註冊的,它們應該是自動調用的,但不知何故它不會(這仍然是個謎)。

    從清單中刪除了所有接收者,並保持廣播接收者的動態註冊,現在代碼與以前一樣工作,只是沒有例外。

    感謝您的幫助。 :)

    1

    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)。