This Handler class should be static or leaks might occur. 大概意思是:Handler类应该定义成静态类,否则可能导致内存泄露。
查询资料,比较统一的解决方法如下所示:
Handler objects for the same thread all share a common Looper object, which they post messages to and read from.
As messages contain target Handler, as long as there are messages with target handler in the message queue, the handler cannot be garbage collected. If handler is not static, your Activity cannot be garbage collected, even after being destroyed.
This may lead to memory leaks, for some time at least - as long as the messages stay int the queue. This is not much of an issue unless you post long delayed messages.
So, you can make your Handler static and have a WeakReference to your Activity.
也就是说:
Handler类应该应该为static类型,否则有可能造成泄露。在程序消息队列中排队的消息保持了对目标Handler类的应用。如果Handler是个内部类,那么它也会保持它所在的外部类的引用。为了避免泄露这个外部类,应该将Handler声明为static嵌套类,并且使用对外部类的弱应用。
eg:
1 public class SplashActivity extends Activity { 2 3 static class SplashHandler extends Handler { 4 5 WeakReferencemActivity; 6 7 SplashHandler(SplashActivity activity) { 8 mActivity = new WeakReference (activity); 9 }10 11 public void handleMessage(Message msg) {12 // TODO Auto-generated method stub13 switch (msg.what) {14 case 0:15 Intent intent = new Intent();16 intent.setClass(mActivity.get(), MainActivity.class);17 mActivity.get().startActivity(intent);18 mActivity.get().finish();19 break;20 default:21 break;22 }23 super.handleMessage(msg);24 }25 } 26 27 @Override28 protected void onCreate(Bundle savedInstanceState) {29 super.onCreate(savedInstanceState);30 requestWindowFeature(Window.FEATURE_NO_TITLE);31 setContentView(R.layout.activity_splash);32 33 SplashHandler mSplashHandler = new SplashHandler(this);34 mSplashHandler.sendEmptyMessageDelayed(0, 2000);35 }36 }