首先解释下这句话This Handler class should be static or leaks might occur,大致意思就是说:Handler类应该定义成静态类,否则可能导致内存泄露。

具体如何解决,在国外有人提出,如下:

Issue: Ensures that Handler classes do not hold on to a reference to an outer class

In Android, Handler classes should be static or leaks might occur. Messages enqueued on the application thread's MessageQueue also retain their target Handler. If the Handler is an inner class, its outer class will be retained as well. To avoid leaking the outer class, declare the Handler as a static nested class with a WeakReference to its outer class.

大体翻译如下:

Handler 类应该应该为static类型,否则有可能造成泄露。在程序消息队列中排队的消息保持了对目标Handler类的应用。如果Handler是个内部类,那 么它也会保持它所在的外部类的引用。为了避免泄露这个外部类,应该将Handler声明为static嵌套类,并且使用对外部类的弱应用。

使用范例:

  1. static
    class MyHandler extends Handler {
  2.                 WeakReference<PopupActivity> mActivity;
  3.  
     
  4.                 MyHandler(PopupActivity activity) {
  5.                         mActivity = new WeakReference<PopupActivity>(activity);
  6.                 }
  7.  
     
  8.                 @Override
  9.                 public
    void handleMessage(Message msg) {
  10.                         PopupActivity theActivity = mActivity.get();
  11.                         switch (msg.what) {
  12.                         case 0:
  13.                                 theActivity.popPlay.setChecked(true);
  14.                                 break;
  15.                         }
  16.                 }
  17.         };
  18.  
     
  19.         MyHandler ttsHandler = new MyHandler(this);
  20.         private Cursor mCursor;
  21.  
     
  22.         private
    void test() {
  23.                 ttsHandler.sendEmptyMessage(0);
  24.         }

原文:http://www.cnblogs.com/savagemorgan/archive/2013/01/23/2872371.html

疑问:是否有其它解决方法?

这个提示就是由于Handler的直接引用会导致相关的Activity、Service等无法被GC。如果这么弱应用的话,会出现空指针,有其它解决方法?

抽时间研究下。

==================================================================================================================================

原始代码:

  1. public
    class MainActivity extends Activity {
  2.  
  3.    private
    static
    int urlIndex = 0;
  4.    private
    final
    static String TAG = MainActivity.class.getSimpleName();
  5.    private
    static
    final String[] url = {
  6.          "http://vdn.apps.cntv.cn/api/getLiveUrlCommonRedirectApi.do?channel=pa://cctv_p2p_hdcctv1&type=ipad",
  7.          "http://74.82.62.53:1935/liverepeater/13.stream/playlist.m3u8", "http://rtmp.cntv.lxdns.com/live/cctv3/playlist.m3u8", };
  8.  
  9.    private
    static
    final
    int MSG_PLAY = 100;
  10.    private
    static
    final
    int MSG_RUN_ADB = 101;
  11.    Handler playHandler = new Handler() {
  12.       @Override
  13.       public
    void handleMessage(Message msg) {
  14.          switch (msg.what) {
  15.          case MSG_PLAY:
  16.             urlIndex = urlIndex > url.length - 1 ? 0 : urlIndex;
  17.             videoView.setVideoPath(url[urlIndex]);
  18.             ++urlIndex;
  19.             break;
  20.          case MSG_RUN_ADB:
  21.             killMediaServer();
  22.             break;
  23.          }
  24.       }
  25.    };
  26.  
  27.  
  28.  
  29.    @Override
  30.    protected
    void onCreate(Bundle savedInstanceState) {
  31.       super.onCreate(savedInstanceState);
  32.       requestWindowFeature(Window.FEATURE_NO_TITLE);
  33.       HHVideoView.create();
  34.  
  35.       setContentView(R.layout.activity_main);
  36.       videoView = ((HHVideoView) findViewById(R.id.videoView));
  37.       videoView.setOnPreparedListener(mPreparedListener);
  38.       videoView.setOnCompletionListener(mCompletionListener);
  39.       videoView.setOnErrorListener(mOnErrorListener);
  40.  
  41.       playHandler.sendEmptyMessage(MSG_PLAY);
  42.  
  43.    }
  44.  
  45.    private HHVideoView videoView = null;
  46.    private MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
  47.       public
    void onPrepared(MediaPlayer paramMediaPlayer) {
  48.          // playerHandler.sendEmptyMessage(uiAction.MEDIAPLAYER_ONPREPAREED);
  49.          videoView.start();
  50.       }
  51.    };
  52.  
  53.    private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
  54.       public
    void onCompletion(MediaPlayer paramMediaPlayer) {
  55.  
  56.       }
  57.    };
  58.    private MediaPlayer.OnErrorListener mOnErrorListener = new MediaPlayer.OnErrorListener() {
  59.       public
    boolean onError(MediaPlayer paramMediaPlayer, int paramInt1, int paramInt2) {
  60.  
  61.          return
    false;
  62.       }
  63.    };
  64.  
  65.    @Override
  66.    public
    boolean onCreateOptionsMenu(Menu menu) {
  67.       // Inflate the menu; this adds items to the action bar if it is present.
  68.       return
    true;
  69.    }
  70.  
  71.    public
    boolean onKeyDown(int keyCode, KeyEvent event) {
  72.       if (event.getAction() == KeyEvent.ACTION_DOWN) {
  73.          switch (keyCode) {
  74.  
  75.          case KeyEvent.KEYCODE_0:
  76.  
  77.             playHandler.sendEmptyMessage(MSG_RUN_ADB);
  78.             break;
  79.  
  80.          case KeyEvent.KEYCODE_DPAD_DOWN:
  81.          case KeyEvent.KEYCODE_DPAD_UP:
  82.  
  83.             playHandler.sendEmptyMessage(MSG_PLAY);
  84.             break;
  85.          }
  86.       }
  87.       return
    super.onKeyDown(keyCode, event);
  88.  
  89.    }
  90.  
  91. }

修改后的代码:

  1. //activity code
  2. public
    class MainActivity extends Activity {
  3.  
  4.    private
    static
    int urlIndex = 0;
  5.    private
    final
    static String TAG = MainActivity.class.getSimpleName();
  6.    private
    static
    final String[] url = {
  7.          "http://vdn.apps.cntv.cn/api/getLiveUrlCommonRedirectApi.do?channel=pa://cctv_p2p_hdcctv1&type=ipad",
  8.          "http://74.82.62.53:1935/liverepeater/13.stream/playlist.m3u8", "http://rtmp.cntv.lxdns.com/live/cctv3/playlist.m3u8", };
  9.  
  10.    PlayHandler playHandler ;
  11.  
  12.  
  13.  
  14.    @Override
  15.    protected
    void onCreate(Bundle savedInstanceState) {
  16.       super.onCreate(savedInstanceState);
  17.       requestWindowFeature(Window.FEATURE_NO_TITLE);
  18.       HHVideoView.create();
  19.  
  20.       setContentView(R.layout.activity_main);
  21.       videoView = ((HHVideoView) findViewById(R.id.videoView));
  22.       videoView.setOnPreparedListener(mPreparedListener);
  23.       videoView.setOnCompletionListener(mCompletionListener);
  24.       videoView.setOnErrorListener(mOnErrorListener);
  25.  
  26.       playHandler.sendEmptyMessage(PlayHandler.MSG_PLAY);
  27.  
  28.    }
  29.  
  30.    private HHVideoView videoView = null;
  31.    private MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
  32.       public
    void onPrepared(MediaPlayer paramMediaPlayer) {
  33.          // playerHandler.sendEmptyMessage(uiAction.MEDIAPLAYER_ONPREPAREED);
  34.          videoView.start();
  35.       }
  36.    };
  37.  
  38.    private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
  39.       public
    void onCompletion(MediaPlayer paramMediaPlayer) {
  40.  
  41.       }
  42.    };
  43.    private MediaPlayer.OnErrorListener mOnErrorListener = new MediaPlayer.OnErrorListener() {
  44.       public
    boolean onError(MediaPlayer paramMediaPlayer, int paramInt1, int paramInt2) {
  45.  
  46.          return
    false;
  47.       }
  48.    };
  49.  
  50.    @Override
  51.    public
    boolean onCreateOptionsMenu(Menu menu) {
  52.       // Inflate the menu; this adds items to the action bar if it is present.
  53.       return
    true;
  54.    }
  55.  
  56.    public
    boolean onKeyDown(int keyCode, KeyEvent event) {
  57.       if (event.getAction() == KeyEvent.ACTION_DOWN) {
  58.          switch (keyCode) {
  59.  
  60.          case KeyEvent.KEYCODE_0:
  61.  
  62.             playHandler.sendEmptyMessage(PlayHandler.MSG_RUN_ADB);
  63.             break;
  64.  
  65.          case KeyEvent.KEYCODE_DPAD_DOWN:
  66.          case KeyEvent.KEYCODE_DPAD_UP:
  67.  
  68.             playHandler.sendEmptyMessage(PlayHandler.MSG_PLAY);
  69.             break;
  70.          }
  71.       }
  72.       return
    super.onKeyDown(keyCode, event);
  73.  
  74.    }
  75.    public
    void setVideoPath() {
  76.       urlIndex = urlIndex > url.length - 1 ? 0 : urlIndex;
  77.       videoView.setVideoPath(url[urlIndex]);
  78.       ++urlIndex;
  79.    }
  80. }

Handler代码:

  1. //handler code
  2. import java.lang.ref.WeakReference;
  3.  
  4. import android.os.Handler;
  5. import android.os.Message;
  6.  
  7. /**
  8.  * @author jevan
  9.  * @version (1.0 at 2013-7-3)
  10.  *
  11.  */
  12. public
    class PlayHandler extends Handler {
  13.    public
    static
    final
    int MSG_PLAY = 100;
  14.    public
    static
    final
    int MSG_RUN_ADB = 101;
  15.    WeakReference<MainActivity> mActivity;
  16.  
  17.    PlayHandler(MainActivity activity) {
  18.       mActivity = new WeakReference<MainActivity>(activity);
  19.    }
  20.  
  21.    @Override
  22.    public
    void handleMessage(Message msg) {
  23.       MainActivity theActivity = mActivity.get();
  24.       if(theActivity == null)
  25.          return;
  26.       switch (msg.what) {
  27.       case MSG_PLAY:
  28.          theActivity.setVideoPath();
  29.          break;
  30.       case MSG_RUN_ADB:
  31.  
  32.          break;
  33.       }
  34.    }
  35. }

个人还是倾向使用独立的Handler(也就是那个外国人的解决方案),上面反映的Activity会被gc掉,导致参数空指针的问题,其实不能算问题。如果Activity被回收掉,那么Handler应该在使用之前对其状态进行判断。

个人推荐这个解决方法,当然代码会多两行。

This Handler class should be static or leaks might occur Android的更多相关文章

  1. Android“This Handler class should be static or leaks might occur”警告的处理方法

    此文属于转载! 最近用到handle在线程中改变UI,会跟给出“This Handler class should be static or leaks might occur”的警告,网上看了很多解 ...

  2. Android - This Handler class should be static or leaks might occur.

    今天学习了使用 HTTP协议,从Android客户端往Tomcat服务器端以GET发送请求,途中无意中发现自己写的Handler类被Android提示:This Handler class shoul ...

  3. This Handler class should be static or leaks might occur(null) 解决办法 (转)

    原文链接:http://blog.csdn.net/wuleihenbang/article/details/17126371 首先解释下这句话This Handler class should be ...

  4. android之lint警告This Handler class should be static or leaks might occur

    更新到adt2.0的开发者们可能会在handler上发现这么一条警告:This Handler class should be static or leaks might occur . 首先在ADT ...

  5. This Handler class should be static or leaks might occur,Handler和Context使用的注意事项!

    Android中.在使用到Handler的时候,假设按例如以下代码编写: private Handler handler; @Override public void onCreate(Bundle ...

  6. Handler classes should be static or leaks might occur

    http://droidyue.com/blog/2014/12/28/in-android-handler-classes-should-be-static-or-leaks-might-occur ...

  7. 85、android handler的警告Handler Class Should be Static or Leaks Occur

    转载:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1106/1922.html 在使用Handler更新UI的时候,我是这样写 ...

  8. 【Android】[转] Android Handler应设为static

    android开发中,使用Lint检测时会提示这么一句话 : This Handler class should be static or leaks might occur.意为handler应用s ...

  9. Handler Should be static or leaks Occur?

    解决办法: public class SampleActivity extends Activity { /** * Instances of static inner classes do not ...

随机推荐

  1. angular : ng-animate : ng-show 原理,详解

    这是我第一次写博客,请大家多多指教^^ 拷贝试试 <!DOCTYPE html> <html> <head> <meta http-equiv="C ...

  2. PDO控制、连接数据库

    PDO(PHP Data Objects)是一种在PHP里连接数据库的使用接口.PDO与mysqli曾经被建议用来取代原本PHP在用的mysql相关函数,基于数据库使用的安全性,因为后者欠缺对于SQL ...

  3. IOS中Hybird中数据驱动与脚本驱动的实现

    现在Hybird这块,网上也有很多文章,最近小有研究了下,分享给大家. 什么是Hybird技术? 1.一般是指WebView和Native技术混合而成的一套技术方案 2.也可以理解成,非Native技 ...

  4. Spring+SpringMVC+MyBatis+easyUI整合基础篇(六)maven整合SSM

    写在前面的话   承接前文<Spring+SpringMVC+MyBatis+easyUI整合基础篇(五)讲一下maven>,本篇所讲述的是如何使用maven与原ssm项目整合,使得一个普 ...

  5. 免费的ERP真的那么可怕?请少一些偏见!

    为什么说这个话题,因为看到了太多关于对免费ERP的偏见,也许这也只是那些卖软件的营销策略:从事这个行业的人,应该能看出其中的端倪,但是对于吃瓜群众来说,那就真是误导了... 所以今天发表下自己的看法, ...

  6. Array对象方法属性总结

    属性主要有三个:constructor;length;prototype; constructor(英文意思:构造器):返回对创建此对象的数组函数的引用.例如:var arr=new Array(); ...

  7. 徒手用Java来写个Web服务器和框架吧<第一章:NIO篇>

    因为有个不会存在大量连接的小的Web服务器需求,不至于用上重量级服务器,于是自己动手写一个服务器. 同时也提供了一个简单的Web框架.能够简单的使用了. 大体的需求包括 能够处理HTTP协议. 能够提 ...

  8. Nginx+IIS+Redis 处理Session共享问题 2

    接下来主要说下利用nginx来测试 两台Windows server 1.10.120.131.210 -  端口84部署demo 2.10.120.131.211 -  端口84部署demo ngi ...

  9. 用ajax实现不刷新分页

    今天我们要用ajax做一个分页: 实现Ajax分页: 如果可以的话加上查询条件 找一张表做分页 分页不使用page类 页面不用刷新 Ajax加载数据 <!doctype html> < ...

  10. java操作txt文本(一):遇到指定字符换行

    想法由来:有时查看网页源代码的css文件内容,竟是恼人的压缩后代码(不换行),如下图所示-- 它的可读性很差,所以写了下面这个简单的程序,实现自动换行. 适用条件:遇到指定字符换行(本例中遇到'}'换 ...