天天看點

關于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);
         }