【问题标题】:How do I code a static handler due to: This Handler class should be static or leaks might occur由于以下原因,我如何编写静态处理程序:此处理程序类应该是静态的,否则可能会发生泄漏
【发布时间】:2013-07-02 14:56:10
【问题描述】:

在我的项目中,由于超出了 VM 预算,它不断崩溃。我使用的图片都非常小,但据说它们会不断填满虚拟机。我正在通过 eclipse 工作,并注意到 2 个实例,它给了我以下错误。

这个 Handler 类应该是静态的,否则可能会发生泄漏 (com.quickreaction.BT_screen_menuButtons.2) BT_screen_menuButtons.java /BT_activity_root/src/com/quickreaction line 1091 Android Lint Problem

当我点击这两个链接时,这也是它带给我的源代码。

Handler downloadScreenDataHandler = new Handler(){ 
@Override public void handleMessage(Message msg){ 
if(JSONData.length() < 1){ 
hideProgress(); 
showAlert(getString(R.string.errorTitle), getString(R.string.errorDownloadingData)); 
}else{ 
parseScreenData(JSONData); 
} 
} 
};  

还有..

private Handler buttonImageHandler = new Handler() { 
public void handleMessage(Message msg){ 
//BT_debugger.showIt(activityName + ":buttonImageHandler setting background image for        button."); 
//msg.what will equal the index of the button images array... 

//set the drawable... 
Drawable d; 

//we may need to round the image... 
if(buttonCornerRadius > 0){ 
d = buttonImages.get(msg.what); 

//we have a drawable, our rounding method needs a bitmap... 
Bitmap b = ((BitmapDrawable)d).getBitmap(); 
b = BT_viewUtilities.getRoundedImage(b, buttonCornerRadius); 

//convert it back to a drawable... 
d = new BitmapDrawable(b); 

}else{ 
d = buttonImages.get(msg.what); 
} 
buttonSquares.get(msg.what).setBackgroundDrawable(d); 
buttonSquares.get(msg.what).invalidate(); 

} };

我一直在阅读有关使处理程序静态或弱的堆栈溢出,但不知道如何。任何想法

【问题讨论】:

    标签: android


    【解决方案1】:

    这些关于制作Handler weakstatic 的lint 消息通常可以忽略。如果您正在创建 Handler 并将对它的引用存储在您的活动中,那么当您的活动被销毁时,Handler 也将消失。这里没有泄漏。唯一可能发生泄漏的情况是,当您的活动消失时,消息队列中仍有一条消息用于该Handler。但是,通常情况并非如此。

    查看您的代码后,我得出结论,您不能创建您的Handler static(即:和内部类),因为它需要对其外部类(活动)的引用。此外,将其设为独立类(如 CommonsWare 的答案)也无济于事,因为在实例化独立类时需要传递对活动的引用,因此这无助于解决“泄漏" 要么(如果真的有的话)。不过,它可能会让愚蠢的 LINT 警告消失 :-)

    如果您遇到内存问题,您应该使用 JHAT 或 MAT 之类的堆分析器,并在关注这些愚蠢的 lint 警告之前实际查看内存中的对象。

    另请参阅This Handler class should be static or leaks might occur: final HandlerThis Handler class should be static or leaks might occur: IncomingHandler

    【讨论】:

      【解决方案2】:

      不要使用匿名内部类的实例(例如,new Handler() {}),而是创建一个静态内部类(例如,static class MyHandler extends Handler)或常规 Java 类(class MyHandler extends Handler)并使用它。

      【讨论】:

      • 添加这些代码是否需要更多编码来设置 MyHandler?
      • @user2543132:您只需调用 new MyHandler() 来创建您的 MyHandler 类的实例。
      猜你喜欢
      • 2020-10-30
      • 2013-02-26
      • 1970-01-01
      • 2017-11-02
      • 2013-05-20
      • 2019-09-03
      • 1970-01-01
      • 2013-09-22
      相关资源
      最近更新 更多