2013-03-11 56 views
2

Android:我的活動中定義了一個Handler類,並且出現警告「Handler類應該是靜態的或可能發生泄漏」下面的代碼:「處理程序類應該是靜態的或可能發生泄漏」 - 處理程序引用主要活動變量

Handler messageHandler = new Handler() { 
     // @Override 
     public void handleMessage(Message msg) { 
     try { 
      ... accessing variables defined at the activity level 
      ... doing something very important 
     } 
     super.handleMessage(msg) 
     } 
    } 

但問題是,我的消息處理程序具有對主要活動變量的引用,所以我不能使它成爲靜態的。如何在我的情況下,我可以擺脫這種警告(以正確的方式)?

回答

4

變化

Handler messageHandler = new Handler() { 
     // @Override 
     public void handleMessage(Message msg) { 
     try { 
      ... accessing variables defined at the activity level 
      ... doing something very important 
     } 
     } 
    } 

Handler mIncomingHandler = new Handler(new Handler.Callback() { 
    @Override 
    public boolean handleMessage(Message msg) { 
    } 
}); 

Refercnce: This Handler class should be static or leaks might occur: IncomingHandler

相關問題