I want to make a REST Client with Android and I read about retrofit. When I do some requests with retrofit even if the activity is destroyed the callback is executed.
How can I stop receiving the response after the activity is being destroyed?
apiService.getDummieContent().enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
An Android activity goes through six major lifecycle stages or callbacks. These are: onCreate() , onStart() , onResume() , onPause() , onStop() , and onDestroy() . The system invokes each of these callbacks as an activity enters a new state.
OnDestroy will be called directly from any call to finish() in onCreate, skipping over onStop. onDestroy can be left out after a kill when onStop returns. Starting with Honeycomb, an application is not in the killable state until its onStop() has returned; pre-honeycomb onPause was the killable state.
An activity can frequently transition in and out of the foreground—for example, onPause() is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.
You can declare global variable apiService
Call<ReponseBody> apiService;
and then call api method for instance here getDummieContent().Moreover you can manually check for the if call is cancelled in OnFaliure method. As in my case i was disabling swipeRefreshLayout which was getting null context on DestroyView because onFailure method was only called when view was destroyed, so with the help of this condition i always checked whether it is cancelled after on destroyed hence preventing exception.
apiService.getDummieContent().enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
{
// Do stuff here
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
if(call.isCanceled())
{
Log.e("isCanceled", " isCanceled");// check if it is cancelled on OnDestroy
}
}
});
and in on destory onDestroy
@Override
public void onDestroy() {
super.onDestroy();
call.cancel();
}
You can assign the request to a variable and cancel it on activity destroy:
Call<ReponseBody> call = apiService.getDummieContent();
call.enqueue(...);
@Override
protected void onDestroy() {
super.onDestroy();
call.cancel();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With