Message Handlers and the WeakReference issue
Posted
by
user1058647
on Stack Overflow
See other posts from Stack Overflow
or by user1058647
Published on 2012-10-16T22:57:33Z
Indexed on
2012/10/16
23:00 UTC
Read the original article
Hit count: 231
The following message Handler works fine receiving messages from my service...
private Handler handler = new Handler()
{
public void handleMessage(Message message)
{
Object path = message.obj;
if (message.arg1 == 5 && path != null) //5 means its a single mapleg to plot on the map
{
String myString = (String) message.obj;
Gson gson = new Gson();
MapPlot mapleg = gson.fromJson(myString, MapPlot.class);
myMapView.getOverlays().add(new DirectionPathOverlay(mapleg.fromPoint, mapleg.toPoint));
mc.animateTo(mapleg.toPoint);
}
else
{
if (message.arg1 == RESULT_OK && path != null)
{
Toast.makeText(PSActivity.this, "Service Started" + path.toString(), Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(PSActivity.this,"Service error" + String.valueOf(message.arg1), Toast.LENGTH_LONG).show();
}
}
};
};
However, even though it tests out alright in the AVD (I'm feeding it a large KML file via DDMS) the "object path = message.obj;" line has a WARNING saying "this Handler class should be static else leaks might occur".
But if I say "static Handler handler = new Handler()" it won't compile complaining that I "cannot make a static reference to a non-static field myMapView. If I can't make such references, I can't do anything useful.
This led me into several hours of googling around on this issue and learning more about weakReferences than I ever wanted to know. The often found reccomendation I find is that I should replace...
private Handler handler = new Handler()
with
static class handler extends Handler
{
private final WeakReference<PSActivity> mTarget;
handler(PSActivity target)
{
mTarget = new WeakReference<PSActivity>(target);
}
But this won't compile still complaining that I can't make a static reference to a non-dtatic field. So, my question a week or to ago was "how can I write a message handler for android so my service can send data to my activity. Even though I have working code, the question still stands with the suffix "without leaking memory". Thanks, Gary
© Stack Overflow or respective owner