我有一个非常简单的代码:
package com.example.conn08;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class MainActivity extends Activity
{
private static CustomHandler mHandler;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateUI();
}
private class CustomHandler extends Handler
{
@Override
public void handleMessage(Message msg)
{
MainActivity.this.updateUI();
}
public void sleep(long delayMillis)
{
this.removeMessages(0);
sendMessageDelayed(obtainMessage(0), delayMillis);
}
}
private void updateUI()
{
mHandler.sleep(1000);
Log.v("updateUI", "kokoko");
}
}
但是在
MainActivity.this.updateUI();
我看到了
此Handler类应该是静态的,否则可能会发生泄漏 (com.example.conn08.MainActivity.CustomHandler)
为什么呢?请帮忙
编辑代码:
package com.example.conn08;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateUI();
}
static class CustomHandler extends Handler
{
WeakReference<MainActivity> mActivity;
CustomHandler(MainActivity aFragment)
{
mActivity = new WeakReference<MainActivity>(aFragment);
}
@Override
public void handleMessage(Message message)
{
MainActivity theActivity = mActivity.get();
theActivity.this.updateUI();
}
}
private CustomHandler mHandler = new CustomHandler(this);
private void updateUI()
{
//mHandler.sleep(1000);
Log.v("updateUI", "kokoko");
}
}
我在此处编辑了Handlers and memory leaks in Android,但现在我已将“theActivity无法解析为某种类型”
答案 0 :(得分:0)
更改:
theActivity.this.updateUI();
为:
theActivity.updateUI();
因为当你说“活动”时,就像这样说。