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();

我懂了

这个 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 cannot be resolve to a type”

4

1 回答 1

0

改变:

theActivity.this.updateUI();  

至:

theActivity.updateUI();  

因为当你说 theActivity 时,就像是这样说的。

于 2013-05-16T09:55:47.850 回答