我正在开发一个android服务,这个服务为应用程序提供了一个AIDL接口,现在应用程序使用AIDL接口调用函数GetData(),这个函数是在service中实现的,它做一些网络操作,连接到服务器并获取一些数据,这个网络事务发生在后台线程中,问题是我希望函数GetData()在网络操作完成之前不应该返回,结果来自服务器,我想将其返回到GetData()中,GetData函数立即返回,后台线程中的网络操作继续并行运行,如何避免这种情况,不能在主线程中调用网络操作。我读了关于countDownlatch的文章,这是唯一可能的解决方案吗?
Service Main Thread
GetData
GetDataFromServer-----------> in Background thread
/*this is problem */ GetData returns; |
|
|
communication in progress
|
|
|
/*I want GetData should return here <-------------------transaction complete
创建一些接口并在您的类中实现该接口,并在网络响应将数据传递给该接口对象后将接口对象传递给特定的服务。
我想这对你有帮助。
你可以从AsyncTask调用startService。我可以有同样的问题在我最近的地方应用程序,需要从谷歌地图的数据。enter code here
protected void getLocationAndUpdatePlaces(boolean updateWhenLocationChanges) {
// This isn't directly affecting the UI, so put it on a worker thread.
AsyncTask<Void, Void, Void> findLastLocationTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// Find the last known location, specifying a required accuracy of within the min distance between updates
// and a required latency of the minimum time required between updates.
// start a service that require data from web.
}
};
findLastLocationTask.execute();
"