Search code examples
androidrestservice

ResultReceiver doesn't survire to screen rotation


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?


Solution

  • I am using a BroadcastReceiver registered using LocalBroadcastManager and it is working properly. It wasn't so simple. Does a better solution exist?