This handler class should be static or leaks might occur
问题描述
在Handler使用方法一文,谈到了Handler的用法,但示例代码中有Warning: this handler class should be static or leaks might occur.
网上有较多的解决办法,这里记录用独立的Handler子类的方法。
public class MyHandler extends Handler
把原来MainActivie中定义的inner class Handler独立出来:
package com.example.handlerexample;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MyHandler extends Handler {
private TextView textView = null;
public MyHandler(TextView textView) {
this.textView = textView;
}
@Override
public void handleMessage(Message msg) {
int count = msg.what;
textView.setText("" + count);
}
}
MainActivity中的优化
public class MainActivity extends Activity {
private Handler handler = null;
/*private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
int count = msg.what;
progress.setText("" + count);
}
};*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
start = (Button) findViewById(R.id.start);
progress = (TextView) findViewById(R.id.progress);
handler = new MyHandler(progress);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
calculate();
}
});
}
另一种方法
protected static final String TAG = "MainActivity";
private Button start = null;
private TextView progress = null;
private static class AnotherHandler extends Handler {
WeakReference<MainActivity> activity = null;
public AnotherHandler(MainActivity activity) {
this.activity = new WeakReference<MainActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
if (activity == null) return;
int count = msg.what;
activity.get().getTextView().setText("" + count);
}
}
private Handler handler = new AnotherHandler(this);
/*private static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
int count = msg.what;
progress.setText("" + count);
}
};*/
private Runnable adding = new Runnable() {
@Override
public void run() {
double d;
for (int count = 1; count <= 1000; count++) {
for (int i = 0; i < 1000; i++) {
d = Math.sqrt(Math.sqrt(i));
Log.d(TAG, "count = " + count + ", sqrt(sqrt(" + i + "))=" + d);
}
if (count % 10 == 0) {
handler.sendEmptyMessage(count / 100);
}
}
}
};
private void calculate() {
Thread thread = new Thread(null, adding, "adding");
thread.start();
}
public TextView getTextView() {
return progress;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
start = (Button) findViewById(R.id.start);
progress = (TextView) findViewById(R.id.progress);
//handler = new MyHandler(progress);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
calculate();
}
});
}