我有一个代码,我在map片段之前调用函数(getData),以便从我调用showList函数执行该函数,但这仅在OnMapready函数之后执行。我其实不知道背后的原因。系统首先说在主线程中完成了更多的工作,所以跳过49帧以清除这个我执行的Showlist,即使是异步任务,但是在ShowList()之前调用map函数。有人说我背后的原因。我知道有一些逻辑,但不知道它是什么? 我的代码
public class GetCo extends FragmentActivity implements OnMapReadyCallback {
String path1la, path1lo, path2la, path2lo;
double dsla, dslo, ddla, ddlo, dp1la, dp1lo, dp2la, dp2lo;
private GoogleMap mMap;
public String myJSON;
private static final String TAG_RESULT = "RESULT";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "Taskname";
private static final String TAG_KILOMETER = "Kilometer";
private static final String TAG_TIMING = "Timing";
private static final String TAG_SOLA = "SourceLa";
private static final String TAG_SOLO = "SourceLo";
private static final String TAG_DLA = "DestinationLa";
private static final String TAG_DLO = "DestinationLo";
private static final String TAG_P1LA = "Path1La";
private static final String TAG_P1LO = "Path1Lo";
private static final String TAG_P2LA = "Path2La";
private static final String TAG_P2LO = "Path2Lo";
JSONArray array = null;
String id, name, kmeter, time, sla, slo, p1la, p1lo, p2la, p2lo, dla, dlo;
TableLayout tl;
TableRow tr;
int c, vt;
TextView tn, kms, tm;
Button map;
String result=null;
String task;
@Override
public void onCreate(Bundle savedInstanceState) {
Intent in = getIntent();
task = in.getExtras().getString("task");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
getData();
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.authority("www.futuroitsolutions.in")
.appendPath("php_android_api")
.appendPath("datare.php")
.appendQueryParameter("Taskname", task);
String myUrl = builder.build().toString();
Log.d("String",task);
Log.d("url",myUrl);
HttpGet httpget = new HttpGet(myUrl);
// Depends on your web service
httpget.setHeader("Content-type", "application/json");
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
@Override
protected void onPostExecute(String result) {
myJSON=result;
Log.d("jsooon",myJSON);
ShowList(myJSON);
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
public void ShowList(String json) {
final String vi = json;
{
class GetData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try {
JSONObject j = null;
j = new JSONObject(vi);
// String notes = j.getString("result");
array = j.getJSONArray("result");
for (int i = 0; i < array.length(); i++) {
JSONObject c = array.getJSONObject(i);
id = c.getString(TAG_ID);
name = c.getString(TAG_NAME);
kmeter = c.getString(TAG_KILOMETER);
time = c.getString(TAG_TIMING);
sla = c.getString(TAG_SOLA);
slo = c.getString(TAG_SOLO);
p1la = c.getString(TAG_P1LA);
p1lo = c.getString(TAG_P1LO);
p2la = c.getString(TAG_P2LA);
p2lo = c.getString(TAG_P2LO);
dla = c.getString(TAG_DLA);
dlo = c.getString(TAG_DLO);
vt = array.length();
String v = String.valueOf(c);
String x = String.valueOf(vt);
Log.d("tagggggg", v);
Log.d("tag", name);
Log.d("tag", kmeter);
Log.d("tag", time);
Log.d("tag", x);
Log.d("lat", sla);
Log.d("log", slo);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
}
}
GetData g = new GetData();
g.execute();
}
}
public void onMapReady(GoogleMap googleMap) {
Log.d("start","first");
mMap = googleMap;
// dsla = Double.parseDouble(sla);
try {
// sla = URLEncoder.encode(sla, "UTF-8");
Log.d("inmap", sla);
dsla = Double.parseDouble(sla);
// slo = URLEncoder.encode(slo, "UTF-8");
dslo = Double.parseDouble(slo);
//path1la = URLEncoder.encode(path1la, "UTF-8");
dp1la = Double.parseDouble(path1la);
// path1lo = URLEncoder.encode(path1lo, "UTF-8");
dp1lo = Double.parseDouble(path1lo);
// path2la = URLEncoder.encode(path2la, "UTF-8");
dp2la = Double.parseDouble(path2la);
// path2lo = URLEncoder.encode(path2lo, "UTF-8");
dp2lo = Double.parseDouble(path2lo);
// dla = URLEncoder.encode(dla, "UTF-8");
ddla = Double.parseDouble(dla);
// dlo = URLEncoder.encode(dlo, "UTF-8");
ddlo = Double.parseDouble(dlo);
} catch (Exception e) {
}
String url1 = getMapsApiDirectionsUrl(dsla,dslo,dp1la,dp1lo,ddla,ddlo);
new connectAsyncTask(url1).execute();
// Getting JSON from URL
// Add a marker in Sydney and move the camera
LatLng kakkanad = new LatLng(10.007243, 76.354628);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(kakkanad, 18));
// mMap.addMarker(new MarkerOptions()
// .position(kakkanad)
// .title("Marker in kakkanad"));
//mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Source, 18));
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
public String getMapsApiDirectionsUrl(double dsla,double dslo,double dp1la,double dp2lo,double ddla,double ddlo) {
//Log.d("in func",sla);
String c=String.valueOf(dsla);
Log.d("in func",c);
final LatLng source = new LatLng(dsla, dslo);
final LatLng path1 = new LatLng(dp1la, dp2lo);
final LatLng path2 = new LatLng(dp2la, dp2lo);
final LatLng dest = new LatLng(ddla, ddlo);
String origin = "", waypoints = "", destination = "";
try {
origin = "origin=" + URLEncoder.encode(String.valueOf(source.latitude), "UTF-8") + "," + URLEncoder.encode(String.valueOf(source.longitude), "UTF-8");
waypoints = "waypoints=" + URLEncoder.encode(String.valueOf(path1.latitude), "UTF-8") + "," + URLEncoder.encode(String.valueOf(path1.longitude), "UTF-8");
destination = "destination=" + URLEncoder.encode(String.valueOf(dest.latitude), "UTF-8") + "," + URLEncoder.encode(String.valueOf(dest.longitude), "UTF-8");
} catch (UnsupportedEncodingException e) {
}
String way = "", sour = "", desty = "";
try {
way = URLEncoder.encode(waypoints, "UTF-8");
desty = URLEncoder.encode(destination, "UTF-8");
sour = URLEncoder.encode(origin, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
String key = "key=AIzaSyDOidVs6_dHl0cjEJ0-OhMfUY0oNFf1SOE";
String params = origin + "&" + destination + "&" + waypoints + "&" + key;
String output = "json";
// https://maps.googleapis.com/maps/api/directions/json?origin=Boston,MA&destination=Concord,MA&waypoints=Charlestown,MA|Lexington,MA&key=YOUR_API_KEY
// String url1="https://maps.googleapis.com/maps/api/directions/json?origin=edapally,kerala&destination=ernakulam,kerala&waypoints=optimize:true|palarivattom,kerala|vytilla,kerala&key=AIzaSyDOidVs6_dHl0cjEJ0-OhMfUY0oNFf1SOE";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
Log.d("taqg", url);
return url;
}
public void drawPath(String result) {
if (result != null) {
mMap.clear();
}
int height = 100;
int width = 100;
BitmapDrawable bitmapdraw = (BitmapDrawable) getResources().getDrawable(R.drawable.source);
Bitmap b = bitmapdraw.getBitmap();
Bitmap ssource = Bitmap.createScaledBitmap(b, width, height, false);
BitmapDrawable bitmapdraw1 = (BitmapDrawable) getResources().getDrawable(R.drawable.way);
Bitmap b1 = bitmapdraw1.getBitmap();
Bitmap sway = Bitmap.createScaledBitmap(
b1, width, height, false);
BitmapDrawable bitmapdraw2 = (BitmapDrawable) getResources().getDrawable(R.drawable.dest);
Bitmap b2 = bitmapdraw2.getBitmap();
Bitmap sdest = Bitmap.createScaledBitmap(b2, width, height, false);
LatLng Source = new LatLng(dsla, dslo);
mMap.addMarker(new MarkerOptions()
.position(Source)
.title("Source")
.icon(BitmapDescriptorFactory.fromBitmap(ssource)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Source, 18));
LatLng path1 = new LatLng(dp1la, dp1lo);
mMap.addMarker(new MarkerOptions()
.position(path1)
.title("path")
.icon(BitmapDescriptorFactory.fromBitmap(sway)));
LatLng path2 = new LatLng(dp2la, dp2lo);
mMap.addMarker(new MarkerOptions()
.position(path2)
.title("path")
.icon(BitmapDescriptorFactory.fromBitmap(sway)));
LatLng dest = new LatLng(ddla, ddlo);
mMap.addMarker(new MarkerOptions()
.position(dest)
.title("Destination")
.icon(BitmapDescriptorFactory.fromBitmap(sdest)));
try {
// Tranform the string into a json object
final JSONObject json = new JSONObject(result);
Log.d("array", result);
JSONArray routeArray = json.getJSONArray("routes");
int i = routeArray.length();
String x = String.valueOf(i);
Log.d("length", x);
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#FF0000"))//Google maps blue color
.geodesic(true)
);
/* for (int z = 0; z < list.size() - 1; z++) {
LatLng src = list.get(z);
LatLng desti = list.get(z + 1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude),
new LatLng(path1.latitude,path1.longitude),
new LatLng(path2.latitude,path2.longitude),
new LatLng(desti.latitude, desti.longitude))
.width(5).color(Color.BLUE).geodesic(true));
}
*/
} catch (Exception e) {
e.printStackTrace();
}
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
private class connectAsyncTask extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass) {
url = urlPass;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(GetCo.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
Log.d("jsonnnnnnnnnnnnnnn", json);
return json;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if (result != null) {
Log.d("jsonppp", result);
drawPath(result);
}
}
}
}