天天看点

关于This Handler class should be static or leaks might occur

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

           首先在ADT 20 Changes我们可以找到这样一个变化:New Lint Checks:

           Look for handler leaks: This check makes sure that a handler inner class does not hold an implicit reference to its outer class.

             翻译过来就是,Lint会增加一个检查项目即:确保class内部的handler不含有外部类的隐式引用 。

            同一个线程下的handler共享一个looper对象,消息中保留了对handler的引用,只要有消息在队列中,那么handler便无法被回收,如果handler不是static那么使用Handler的Service和Activity就也无法被回收。这就可能导致内存泄露。当然这通常不会发生,除非你发送了一个延时很长的消息。

private static Handler handler;

                 public void onCreate(Bundle savedInstanceState) {
                         super.onCreate(savedInstanceState);
                         setContentView(R.layout.main); // Create a handler to update the UI
                         handler = new Handler();
                 }

                 void test() {
                         handler.post(new MyRunnable());// 这样的方法同样可以用 SmsPopupActivity.this.runOnUiThread(new MyRunnalble());来替换,效果是一样的。
                 }

                 static public class MyRunnable implements Runnable {
                         @Override
                         public void run() {
                                 imageView.setImageBitmap(downloadBitmap);
                                 dialog.dismiss();
                         }
                 }      
MyHandler(PopupActivity activity) {
                         mActivity = new WeakReference<PopupActivity>(activity);
                 }

                 @Override
                 public void handleMessage(Message msg) {
                         PopupActivity theActivity = mActivity.get();
                         switch (msg.what) {
                         case 0:
                                 theActivity.popPlay.setChecked(true);
                                 break;
                         }
                 }
         };

         MyHandler ttsHandler = new MyHandler(this);
         private Cursor mCursor;

         private void test() {
                 ttsHandler.sendEmptyMessage(0);
         }