Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit From Android Service, Callback Failing When Application is In Background/Closed

I am using Android Service for getting location via fused location API and retrofit API to update location within specific time interval.

All is working fine when application is open/foreground. But when application is background/closed all things is working except retrofit request.

Retrofit callbacks getting failure with message "Failed to connect to ". When application opens again everything working perfect.

Retrofit 2 Callback onResponse on background thread or Services always onFailure

Any help would be much appriciated. Thanks

This Service is starting from TimeTask:

public class SendLocationService extends IntentService {
private static final String TAG = "SendLocationService";
private Context mContext = null;
private APIInterface apiInterface;

public SendLocationService() {
    super("SendLocationService");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    mContext = getApplicationContext();
    Log.e(TAG, "**************************************");
    Log.e(TAG, "Location Update Time Interval");
    Log.e(TAG, "**************************************");
    Login login = (Login) CommonMethods.retrieveObject(mContext, PreferenceConnector.LOGIN, new Login());
    if (login == null)
        return;
    List<LocationData> locationData = DatabaseHelper.getInstance(mContext).getAllLocation();
    Log.i(TAG, "Time to hit the APIs: " + DatabaseHelper.getInstance(mContext).getAllLocation().size());
    JSONArray jsonArray = new JSONArray();
    List<TrackedLocation> trackedLocations = new ArrayList<TrackedLocation>();
    for (LocationData data : locationData) {
        try {
            jsonArray.put(new JSONObject(data.getData()));
            Gson gson = new Gson();
            TrackedLocation obj = gson.fromJson(data.getData(), TrackedLocation.class);
            trackedLocations.add(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    HashMap<String, Object> hashMap = new HashMap<String, Object>();
    hashMap.put("EmpId", login.getMessage().getID());
    hashMap.put("MapTrack", trackedLocations);

    if (apiInterface == null) {
        apiInterface = APIClient.getClientInstance().create(APIInterface.class);
    }
    apiInterface.postMapTrackingDetails(hashMap).enqueue(new Callback<Message>() {
        @Override
        public void onResponse(Call<Message> call, Response<Message> response) {
            try {
                DatabaseHelper.getInstance(mContext).deleteLocationData();
                PreferenceConnector.resetLocationCounter(mContext);
                response.body();
                Log.e("response:", response.body().getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<Message> call, Throwable t) {
            try {
                Log.e("response:", t.getLocalizedMessage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

}

like image 407
Mohammad Misbah Avatar asked Apr 26 '18 07:04

Mohammad Misbah


1 Answers

User Intent Service for retrofit api call and all other actions along with BroadCast Receivers, so that you can call code in background with Intent Services and then can react on results with BroadCast Receivers

like image 102
Muhammad Hassaan Avatar answered Sep 27 '22 18:09

Muhammad Hassaan