I'd like to implement two-way communication between my Activity
and an IntentService
via Messaging.
In this Google sample project the Handler
class is implemented as an inner class in the Activity
:
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MessengerService.MSG_SET_VALUE:
mCallbackText.setText("Received from service: " + msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
}
Implementing my Handler
in the same manner results in the following warning:
This Handler class should be static or leaks might occur
So after checking out this answer, i've implemented mine as a static nested class, something like this:
private static class IncomingHandler extends Handler {
private final WeakReference<MainActivity> mainActivity;
IncomingHandler(MainActivity activity) {
mainActivity = new WeakReference<MainActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
MainActivity activity = mainActivity.get();
if(activity != null) {
activity.doStuff();
}
}
}
Is this a safe approach to handle the warning above?
Thanks in advance.