我知道 Handler 可能会在 Android 中泄漏内存,但我不太确定我所做的是否正确:
public class MyActivity extends Activity
{
Handler handler;
HashMap<String, String> bigData = new HashMap<String, String>();
protected void onCreate(undle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new WeakHandler(){
public void handlerMessage(Message msg, Context conetxt)
{
// i think this usage is wrong, still leak, am I right?
Log.v("MyActivity", bigData.get("abc"))
}
}
};
static class WeakHandler extends Handler {
private final WeakReference<Context> ref;
public WeakHandler(Context t) {
super();
ref = new WeakReference<Context>(t);
}
@Override
public final void handleMessage(Message msg) {
final Context context = ref.get();
if (context != null) {
handleMessage(msg, context);
}
}
public void handlerMessage(Message msg, Context conetxt)
{
}
}
另外,如果我只想使用 Handler 来“post”、“postDelayed”、“removeCallbacks”,我不关心 handleMessage,只创建一个新的 Handler 实例来执行此操作是否安全,如下所示:
new Handler().postDelayed(some Runnable);