首页 > 代码库 > Android - This Handler class should be static or leaks might occur.

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

  今天学习了使用 HTTP协议,从Android客户端往Tomcat服务器端以GET发送请求,途中无意中发现自己写的Handler类被Android提示:This Handler class should be static or leaks might occur. 往google上type,发现很多网友都做了解释,也感触颇深,编译器的提示,有时真的要留意,这对自己学习也有很大的帮助.

  虽然多了几行代码,但为了实用,我就上贴自己实际点的例子,Activity:

package spt.http.get.activity;import java.lang.ref.WeakReference;import spt.http.get.assist.SendDataToServer;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {	//view.	private EditText edt_name = null;	private EditText edt_pwd = null;	private Button btn_ok = null;	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		initView();		initListener();	}		/**	 * 初始化View.	 */	private void initView() {		edt_name = (EditText)findViewById(R.id.edt_name);		edt_pwd = (EditText)findViewById(R.id.edt_pwd);		btn_ok = (Button)findViewById(R.id.btn_ok);				//test:		edt_name.setText("你好");		edt_pwd.setText("abc");	}		/**使用静态内部类,解决‘This Handler class should be static or leaks might occur‘,以免造成内存泄露.	 * @author Administrator	 *	 */	private static class StatusHandler extends Handler {		WeakReference<MainActivity>  iMainActivity = null;				public StatusHandler(MainActivity mainActivity) {			iMainActivity = new WeakReference<MainActivity>(mainActivity);		}				@Override		public void handleMessage(Message msg) {			switch (msg.what) {			case SendDataToServer.SEND_SUCCESS:				//有iMainActivity.get()和iMainActivity.getClass().				Toast.makeText(iMainActivity.get(), "发送成功", Toast.LENGTH_SHORT).show();				break;			case SendDataToServer.SEND_FAIL:				Toast.makeText(iMainActivity.get(), "发送失败", Toast.LENGTH_SHORT).show();				break;			default:				throw new RuntimeException("未知的发送结果!");			}		}	}	/**	 * 处理发送是否成功的状态的Handler.	 */	private final  Handler handler = new StatusHandler(this);		/**	 * 初始化监听器.	 */	private void initListener() {		btn_ok.setOnClickListener(new Button.OnClickListener() {						@Override			public void onClick(View v) {				String name = edt_name.getText().toString();				String pwd = edt_pwd.getText().toString();				if(name.isEmpty() || pwd.isEmpty()) {					Toast.makeText(MainActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();					return;				}				new SendDataToServer(handler).send(name, pwd);			}		});	}}

 将Handler声明为static,是为了解决可能出现‘内存泄露‘的问题,因为在一般情况下,通过Handler往消息队列中放入Message对象的时候,Message对象会持有对外部类的隐式引用,而是用static类,则不会对外部类有隐式引用.例如,Message对象引用主线程(UI)的视图等资源,如果不及时被处理,则他引用的对象将被一直占用,被引用的对象可能是很久以后才使用,这样一来,内存将很快被耗尽.

 ref: http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2014/1106/1922.html

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