can activity context be passed around without preventing the OS from destroying it when applicable?
It cannot be the other way: you cannot prevent the destruction of an Activity
. But if you keep a reference to such object, it won't be garbage collected while being of no real use to you. Simply put, a memory leak that you may want to avoid.
An asynchronous request on a socket is made, attached to this is an hashmap where key=request_id and value=activity_context. Upon response, the id is linked to fetch the activity_context and a method in the activity is called (ie using interface, casting etc).
There is nothing particularly wrong which such an approach, but to avoid leaks (and potential crashes caused by them) I suggest removing from the Map
all requests related to Activity
as it goes into destroyed state. If that's possible with your architecture, you can also cancel these request.
That said, it's probably better to follow CommonsWare's advise and use one of the approaches from his comment that are built for such use cases.
I could theorize here and eventually write a whole article on it here, so it would be best if you updated your question with the following information:
- lifecycle of the socket:
Activity
related? one for whole app until process is killed or user logs out?
- when the device configuration is changed and activity is recreated: do you want to receive response to the old request in new
Activity
?
- when you
finish
the Activity
(or user presses BACK) before the response is ready and then return to it after, do you expect to see it?
I am aware of storing weakreferences to the context
The problem with WeakReferences
is that they do not help avoiding leaks. Yes, they help avoiding permanent leaks, where you would keep a bad reference indefinitely, but they do not prevent calls to already destroyed Activity
.
the android OS garbage collection is known to clean up weakreferences in cases where it is still 'alive' with increasing frequency.
Do you mean WeakReference
's reference is nulled while there are strong references to the object? I don't think this can happen.