I'm working on some Activity
code and ran across an Android Studio warning I don't understand. Here is a minimal version of the code that produces the warning:
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
public class TestActivity extends Activity {
private static Handler mActivityHandler = new Handler() {
// Android Studio 1.5.1 warns of a leak here
};
protected void onCreate( Bundle state ) {
super.onCreate( state );
mActivityHandler.sendEmptyMessageDelayed( 0, 10L );
}
}
Android Studio 1.5.1 highlights in yellow the body of the new Handler() { }
where the comment indicates, displaying this message:
Handler reference leaks
Since this Handler is declared as an inner class, it may prevent the outer class from being garbage collected. If the Handler is using a Looper or MessageQueue for a thread other than the main thread, then there is no issue. If the Handler is using the Looper or MessageQueue of the main thread, you need to fix your Handler declaration, as follows: Declare the Handler as a static class; In the outer class, instantiate a WeakReference to the outer class and pass this object to your Handler when you instantiate the Handler; Make all references to members of the outer class using the WeakReference object.
The code runs fine (when the rest of the code that I stripped out for this example is put back in!) but I would like to understand the warning and find a way to fix it.
Is there another way to write the code to avoid this warning?