1 private Handler mHandler = new Handler() { 2 public void handleMessage(Message msg) { 3 switch (msg.what) { 4 case 1: { 5 break; 6 case 2: 7 break; 8 } 9 } 10 };
一般写Handler的时候会向以上这么写,这样写话的话,Eclipse会提示“This Handler class should be static or leaks might occur ” 大概意思是这个Handler类应该是静态的或可能发生泄漏。所以需要修改成以下这种写法。
1 private MyHandler handler; 2 3 private static class MyHandler extends Handler { 4 // PayActivity是本Activity类 5 WeakReference<PayActivity> aaa = null; 6 public MyHandler(PayActivity bbb) { 7 this.aaa = new WeakReference<PayActivity>(bbb); 8 } 9 public void handleMessage(Message msg) { 10 PayActivity payF = aaa.get(); 11 if (payF == null) 12 return; 13 14 switch (msg.what) { 15 case 1: 16 break; 17 case 2: 18 payF.deal(msg); 19 break; 20 } 21 22 }; 23 }; 24 25 // 在onCreate()方法里面实例化MyHandler 26 handler = new MyHandler(this);
这样就O了。