5
我有一個非常簡單的代碼:這個處理程序類應該是靜態的或泄漏可能發生
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");
}
}
我已經例如這裏Handlers and memory leaks in Android在編輯像,但現在我已經 「theActivity不能被解析爲一個類型」
刪除'theActivity.this'並使用'theActivity'。這是對'theActivity.this'的「參考」,所以它是雙倍的。 – tolgap