Reputation: 15509
I understand that the Handler may leak memory in Android, but I am not very sure what I did is correct:
public class MyActivity extends Activity
{
Handler handler;
HashMap<String, String> bigData = new HashMap<String, String>();
protected void onCreate(undle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new WeakHandler(){
public void handlerMessage(Message msg, Context conetxt)
{
// i think this usage is wrong, still leak, am I right?
Log.v("MyActivity", bigData.get("abc"))
}
}
};
static class WeakHandler extends Handler {
private final WeakReference<Context> ref;
public WeakHandler(Context t) {
super();
ref = new WeakReference<Context>(t);
}
@Override
public final void handleMessage(Message msg) {
final Context context = ref.get();
if (context != null) {
handleMessage(msg, context);
}
}
public void handlerMessage(Message msg, Context conetxt)
{
}
}
Also, If I just want to use a Handler to "post", "postDelayed", "removeCallbacks", I do not care about handleMessage, is that safe to just create a new Handler instance to do that, like this:
new Handler().postDelayed(some Runnable);
Upvotes: 0
Views: 2321
Reputation: 2034
When you instantiate the WeakHandler, it won't be an actual WeakHandler class, but an Anonymous class which extends WeakHandler class. An Anonymous class is never static so it will have an implicit reference to the containing class (namely the MyActivity), besides the explicit WeakReference.
Since the onCreate() runs on the main thread, the Handler - that is created inside the onCreate() - will be associated with the main tread (actually the main Looper that is created when the Application starts). If you post a Message (or a Runnable, since the Runnable will be wrapped around with a Message) to the Handler, that Message/Runnable will have a reference to the Handler.
So given you postDelayed something with 5 mins delay. After destroying the Activity (eg. because of rotation), the main Looper will have a reference to the Message/Runnable, the Message/Runnable will have a reference to the Handler, Handler will have a reference to the Activity for 5 mins. This is a leak.
And yes, the "Log.v("MyActivity", bigData.get("abc"))" line leaks the activity as well.
Upvotes: 1
Reputation: 133570
Use MAT Analyzer to check for memory leaks. http://www.youtube.com/watch?v=_CruQY55HOk. The talk is about memory leak.
My guess the reference to the context is causing leaks. Use getApplicationContext();
This context will live as long as your application is alive.
http://android-developers.blogspot.in/2009/01/avoiding-memory-leaks.html.
Upvotes: 0