我正在使用Android Service,通过融合位置API和Retrofit API来获取位置并在特定时间间隔内更新位置。当应用程序处于打开/前台时,一切都正常工作。但是当应用程序处于后台/关闭状态时,所有功能都可以正常运行,除了Retrofit请求。Retrofit回调会失败,并显示消息“无法连接到”。当应用程序再次打开时,一切都正常工作。
无论是在后台线程还是服务中,Retrofit 2的回调均为onFailure。
非常感谢任何帮助。谢谢!
此服务从TimeTask启动:
无论是在后台线程还是服务中,Retrofit 2的回调均为onFailure。
非常感谢任何帮助。谢谢!
此服务从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();
}
}
});
}
}