3
Android的意图服务的工作请求我已经创建了一个IntentService如下:平行运行
public class OrdersSyncService extends IntentService {
private static final String TAG = OrdersSyncService.class.getSimpleName();
private Order orderObject;
public OrdersSyncService() {
super("OrdersSyncService");
}
@Override
protected void onHandleIntent(Intent intent) {
//Util.showToast(getApplicationContext(), "Syncing Orders........");
Log.d(TAG, "I'm running....");
syncOrders();
}
private void syncOrders() {
Database database = CouchBaseHelper.openCouchBaseDB(this);
JSONArray ordersJsonArray = new JSONArray(CouchBaseHelper.retrieveNotSyncedOrders(database));
if (ordersJsonArray.length() != 0) {
uploadOrders(ordersJsonArray.toString());
Log.d(TAG, "Orders syncing started.");
} else {
Log.d(TAG, "Nothing to sync.");
}
}
private void uploadOrders(String ordersJsonArray) {
RetrofitApi.ApiInterface apiInterface = RetrofitApi.getApiInterfaceInstance();
final Call<Order> uploadOrders = apiInterface.uploadOrders(
ordersJsonArray,
Util.getDeviceId(this),
AppPreference.getString(this, AppPreference.USER_ID)
);
uploadOrders.enqueue(new Callback<Order>() {
@Override
public void onResponse(Call<Order> call, Response<Order> response) {
if (response.isSuccessful()) {
if (response.body().getStatus().equals("success")) {
orderObject = response.body();
Log.d(TAG, "Server Response : " + orderObject.getMobileOrderIds());
boolean flag = updateOrders(orderObject);
if (flag) {
Log.d(TAG, "Orders Synced And Updated.");
EventBus.getDefault().post(new SyncFinished(true));
} else {
Log.d(TAG, "Orders Synced But Update Failed.");
}
} else {
Log.d(TAG, response.body().getMessage());
}
} else {
Log.d(TAG, "Some Error. Sync Failed.");
}
}
@Override
public void onFailure(Call<Order> call, Throwable t) {
Log.d(TAG, "Network problem. Sync Failed.");
//Log.d("VICKY",call.request().url().toString());
}
});
}
private boolean updateOrders(Order order) {
Database database = CouchBaseHelper.openCouchBaseDB(this);
boolean flag = CouchBaseHelper.updateOrders(database, order);
return flag;
}
}
它是什么,它使一个网络请求和网络请求后,更新数据库(I” m使用couchbaselite for android)与响应。现在问题在于,当我向它发出多个请求时,它的执行是并行的。 Android文档明确指出: Creating a Background Service
工作请求按顺序运行。如果某个操作正在IntentService中运行,并且您发送了另一个请求,则请求会等待,直到第一个操作完成。
我从一个活动的onResume
方法调用此服务。因此,每当活动恢复时,此服务被称为:
@Override
protected void onResume() {
super.onResume();
Intent ordersSyncServiceIntent = new Intent(SellerHomeActivity.this, OrdersSyncService.class);
startService(ordersSyncServiceIntent);
}
我不知道问题是什么。我认为它与Retrofit
库有关,用于创建异步的网络请求。请帮忙。
好的,我知道我在做异步,但究竟是什么导致我的IntentService并行运行?你能否详细说明一下。 – Vicky
@Vicky,您正在IntentService的另一个线程中产生工作。 IntentService运行,让我们说线程4,并且您正在线程上运行您的网络调用让我们说6。因此,您不使用IntentService类。在这种情况下,您可以使用服务。 – azizbekian
@azizbekian,我明白了,我在IntentService中创建了另一个线程,但是'Retrofit'中的'Callback'应该在IntentService线程上执行,对吧? – Vicky