我试图创建一种方法来获取网站上的某个地点的高度: https://maps.googleapis.com/maps/api/elevation/json?locations=0,0(其中0,0可以用任何坐标替换)。Android getInputStream无法正常工作
但是,从URL连接获取InputStream
时遇到问题。
private double altitude(double lat, double longi) {
String elevation = "";
try {
URL alt = new URL("https://maps.googleapis.com/maps/api/elevation/json?locations="+lat+","+longi);
HttpURLConnection altFind = (HttpURLConnection) alt.openConnection();
altFind.setDoInput(true);
BufferedReader in = new BufferedReader(new InputStreamReader(altFind.getInputStream()));
String inputLine;
OUT:
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("elevation")) {
for (int i = 23; ; i++) {
if (inputLine.charAt(i) != ',') {
elevation = elevation + "" + inputLine.charAt(i);
} else {
break OUT;
}
}
}
}
return Double.parseDouble(elevation);
} catch (MalformedURLException e) {}
catch (IOException e) {}
return 0;
}
这是方法和我把它从这里:
private TextView t;
private LocationManager locationManager;
private LocationListener listener;
double elev;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Intent intent = getIntent();
String longlat = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
longlat = longlat.replaceAll(" ", "");
String [] longilati = longlat.split(",");
final double [] coord = new double[2];
coord[0] = Double.parseDouble(longilati[0]);
coord[1] = Double.parseDouble(longilati[1]);
t = (TextView) findViewById(R.id.textView);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
elev = altitude(coord[0], coord[1]);
} else {
Toast.makeText(this, "No connection available", Toast.LENGTH_LONG).show();
}
我已试过无济于事类似的问题。
请定义“无法正常工作”。你有错误吗?它会崩溃吗?什么是意外? – Knossos
'我从URL连接中获取InputStream时遇到了问题。哪个问题? – greenapps
你将有一个'NetworkOnMainThreadException'。你的应用崩溃了。你应该已经告诉过这一切! – greenapps