我有一个非常简单的代码:
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();
我懂了
这个处理程序类应该是静态的,否则可能会发生泄漏
(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");
}
}
我已经像在这里的示例中那样编辑了它,但是现在我有了“活动不能解析为类型”
最佳答案
变化:
theActivity.this.updateUI();
到:
theActivity.updateUI();
因为当你说活动的时候,就像是在说这个。