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();
}
}
});
}
}
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
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