I am implementing a REST client in Android.
I have seen an example of using a Service
to perform the connection to the server and the ResultReceiver
to be notified of the operation completion. I am calling the service from a fragment and, if I try to rotate the screen while the service is running, the getActivity() method in ResultReceiver
returns null because probably that fragment is not in layout anymore.
The callback method in the fragment:
@Override
public void onReceiveResult(int resultCode, Bundle resultData) {
Response response = (Response) resultData
.getSerializable(RestService.RESULT);
if (resultCode == RestService.SUCCESS
&& response != null) {
if (getActivity() != null) {
recommendationResponse = response;
getLoaderManager().restartLoader(0, new Bundle(),
Fragment.this);
}
}
}
The getActivity()
returns null.
Is this normal? What approach could I use to allow notification even on screen rotation? Local Broadcast?
I am using a
BroadcastReceiver
registered usingLocalBroadcastManager
and it is working properly. It wasn't so simple. Does a better solution exist?Android Activities are recreated after device rotation.
After activity is recreated it does not holds old context.that's why your getting
getActivity()
as nullIf you dont want activity to recreated on screen rotation.mention following in manifest
And last You will have to override following in Activity.
Yes, this normal since the ResultReceiver might be "headless".
I tried saving the
ResultReceiver
atonSaveInstanceState()
, but it didn't work, since updates, that happen while the receivingFragment
is destroyed, get lost, and the references to callbacks too.An explanation and a possible solution can be found here: https://stanmots.blogspot.com/2016/10/androids-bad-company-intentservice.html
Another good read concerning this problem: https://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
My full solution how to use a
ResultReceiver
can be found here: https://stackoverflow.com/a/54334864/6747171No,
is not a solution.
To use ResultReceiver I:
save it on orientation changes:
reset the receiver:
Here is my ResultReceiver class:
I think I stumbled upon the same issue and resolved it by verifying for NULL in the onReceivedResult method of my ResultReceiver. The code posted here works on a worker fragment (fragment without UI and setRetainInstance(true) in onCreate)
The notificationPending flags helps the fragment hold the pending notification if the activity was not found (Activity is not available on fragment Detach).
When the fragment reattaches to the activity i perform this logic
Hope it helps. You can ask for further details if you like. Cheers