gpt4 book ai didi

java - 所有AsyncTasks完成后如何执行onMapReady()回调?

转载 作者:行者123 更新时间:2023-12-01 21:22:04 24 4
gpt4 key购买 nike

我的代码遇到了问题,我的 Activity 用来调用 google api 并检索 json,反序列化它们并使用它的折线在 map 上绘制。

问题是,发送 onMapReady()(用于创建 map )回调的 getMapAsync() 在执行检索必要数据以创建 map 的异步任务后立即执行。

如何在不停止 UI 线程的情况下实现这一点?我尝试调用 .execute.get() 来卡住 UI 线程。但如果我这样做,我将无法使用 ProgressDialog 通知用户从服务器获取数据的延迟,他们将看到卡住的 UI,直到任务完成。我该怎么做?

public class RouteAssistantActivity extends Activity implements OnMapReadyCallback{

public GoogleMapsDirectionsResponse dirRes;
public GoogleMapsDistanceResponse disRes;

public String jsonString;
private String mapsAPIKey;
private String directionsBaseURL;
private String distanceBaseURL;

MapFragment mapFragment;
private ProgressDialog progress;

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ra_route_assisstant);

mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.ra_map);
progress = new ProgressDialog(RouteAssistantActivity.this);
progress.setTitle("Please Wait");
progress.setMessage("Retrieving Data from the Server");
progress.setIndeterminate(true);

try {
ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);

if (appInfo.metaData != null) {
mapsAPIKey = appInfo.metaData.getString("com.google.android.maps.v2.API_KEY");
directionsBaseURL = appInfo.metaData.getString("com.google.android.maps.directions.baseURL");
distanceBaseURL = appInfo.metaData.getString("com.google.android.maps.distance.baseURL");
}

} catch (PackageManager.NameNotFoundException e) {
Log.e("Meta Error", "Meta Data not found. Please check the Manifest and the Meta Data Package Names");
e.printStackTrace();
}

//Test
String directionsURL = directionsBaseURL+"origin=6.948109,79.858191&destination=6.910176,79.894347&key="+mapsAPIKey;
String distanceURL = distanceBaseURL+"units=metric&origins=6.948109,79.858191&destinations=6.910176,79.894347&key="+mapsAPIKey;

Log.e("CA Debug","URL : " + directionsURL);
Log.e("CA Debug","URL : " + distanceURL);

new configurationSyncTask().execute(distanceURL,"distance");
new configurationSyncTask().execute(directionsURL, "direction");

mapFragment.getMapAsync(this);

}

@Override
public void onMapReady(GoogleMap googleMap) {
LatLng rajagiriya = new LatLng(6.910176, 79.894347);

String points = dirRes.getRoutes().get(0).getOverviewPolyline();
List<LatLng> list = PolyUtil.decode(points);

googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(rajagiriya, 13));

googleMap.addMarker(new MarkerOptions()
.title("Rajagiriya")
.snippet("My Place")
.position(rajagiriya));

googleMap.addPolyline(new PolylineOptions()
.geodesic(false)
.addAll(list)
.color(Color.RED)
.width(25));
}

private class configurationSyncTask extends AsyncTask<String, Void, String> {

@Override
protected void onPreExecute() {
progress.show();
}

@Override
protected String doInBackground(String... params) {

String url = params[0];
String type = params[1];

Log.d("CA Debug", getClass().getSimpleName() + " --> Real URL : " + url);
Log.d("CA Debug", getClass().getSimpleName() + " --> doInBackground requesting content");

jsonString = requestContent(url);

// if the output is null, stop the current task
if (jsonString == null) {
Log.d("CA Debug", getClass().getSimpleName() + " --> Stopping Async Task");
this.cancel(true);
Log.d("CA Debug", getClass().getSimpleName() + " --> Async Task Stopped");
}

return type;
}

@Override
protected void onPostExecute(String types) {

if (types.equalsIgnoreCase("distance")) {
disRes = GMapsDistanceResponseJSONDeserializer.deserialize(jsonString);
} if (types.equalsIgnoreCase("directions")) {
dirRes = GMapsDirectionsResponseJSONDeserializer.deserialize(jsonString);
}

progress.dismiss();
}


}

public String requestContent(String url) {

Log.d("CA Debug",getClass().getSimpleName()+" --> URL : "+url);

try {
URL urlObj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) urlObj.openConnection();
con.setChunkedStreamingMode(0);
con.setRequestMethod("GET");

SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null,null, new SecureRandom());
con.setSSLSocketFactory(sc.getSocketFactory());

InputStream clientResponse;
String jsonString;
int status = con.getResponseCode();

if(status >= HttpURLConnection.HTTP_BAD_REQUEST){
Log.d("CA Debug", getClass().getSimpleName()+" --> Bad Request");
jsonString = null;
} else {
Log.d("CA Debug", getClass().getSimpleName()+" --> converting Stream To String");
clientResponse = con.getInputStream();
jsonString = convertStreamToString(clientResponse);
}

Log.d("CA Debug", getClass().getSimpleName()+" --> JSON STRING : " + jsonString);

return jsonString;
} catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {

Log.d("CA Debug", getClass().getSimpleName()+" --> Error when creating an Input Stream");
e.printStackTrace();

}
return null;
}

public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;

try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}

return sb.toString();
}

}

最佳答案

快速但有些肮脏的解决方案是在单个 AsyncTask 上执行两个 AsyncTask,然后在其 onPostExecute 代码上调用 getMapAsync。这样您就可以在处理 map 准备就绪之前确保任务已完成。

关于java - 所有AsyncTasks完成后如何执行onMapReady()回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38971038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com