2012-11-10 12 views
5

Mam bardzo prosty kod:Ta klasa Handler powinny być statyczne lub przecieki mogą wystąpić

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"); 
    } 
} 

ale w

MainActivity.this.updateUI(); 

widzę

klasa

Ten Handler powinna być statyczna lub mogą wystąpić przecieki (com.example.conn08.MainActivity.CustomHandler)

Dlaczego? pomóc proszę


redakcją kod:

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"); 
    } 

} 

Mam edytowany go jak w przykładzie tutaj Handlers and memory leaks in Android, ale teraz mam "theActivity nie może być rozwiązany do typu"

+1

upuść 'theActivity.this' i po prostu użyj' theActivity'. To 'Reference' do twojego' theActivity.this', więc jest podwójne. – tolgap

Odpowiedz

0

Zmiana:

theActivity.this.updateUI(); 

do:

theActivity.updateUI(); 

ponieważ kiedy mówisz o "Rzeczywistości", to tak, jakby to powiedzieć.

Powiązane problemy