安卓服务中的 Retrofit,当应用在后台/关闭时回调失败

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

}


嗨,你有这个问题的解决方案吗? - Avinash Ajay Pandey
是的,仅针对此API跳过了Retrofit,使用HttpURLConnection将值更新到服务器。 - Mohammad Misbah
2个回答

1
用户意图服务用于Retrofit API调用和其他所有操作,以及广播接收器,这样您就可以使用意图服务在后台调用代码,然后可以使用广播接收器对结果进行反应。

也尝试使用了BroadCastReceiver,但是问题依旧。 - Mohammad Misbah
代码已添加,此服务从位置服务的TimeTask开始,其设置为每5分钟一次的时间间隔。 - Mohammad Misbah

0

替换以下行:

DatabaseHelper.getInstance(mContext).deleteLocationData();
            PreferenceConnector.resetLocationCounter(mContext);
            response.body();

使用:

if (mContext != null)
{
    DatabaseHelper.getInstance(mContext).deleteLocationData();
    PreferenceConnector.resetLocationCounter(mContext);
    response.body();
}

谢谢@Saad,这不是问题。问题在于,当应用程序处于后台/关闭状态时,我无法进入onResponse,而总是通过"Failed to connect to /<HostURL>"消息进入onFailure。当应用程序处于前台时,相同的回调正常工作即onResponse - Mohammad Misbah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接