Android getInputStream无法正常工作

时间:2016-12-02 10:13:30

标签: java android

我正在尝试创建一种从网站获取某个地点的高度的方法: https://maps.googleapis.com/maps/api/elevation/json?locations=0,0(其中0,0可以替换为任何坐标)。

但是,从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();
    }

我尝试过类似的问题但没有用。

1 个答案:

答案 0 :(得分:1)

您应该在后台线程上执行网络连接。

您可以使用Asynctask课程并在altitude内移动doInBackground()方法。

您可以在这里阅读更多内容: https://developer.android.com/reference/android/os/AsyncTask.html

编辑:

我发现这个名为JSONParser的课程,我认为这就是你需要的,请查看: https://gist.github.com/dmnugent80/b2e22e5546c4b1c391ee

将其复制并粘贴到您的项目中。

您可以通过从altitude类调用makeHttpRequest方法并传递所需的所有参数来修改JSONParser方法。如果你做得对,那么该方法将从URL返回JSON对象。例如:

private static final String URL = "https://maps.googleapis.com/maps/api/elevation/json";
private static final String METHOD = "GET"; // You can use POST either

private double altitude(double lat, double lng) {
    double elevation = 0.0;
    HashMap<String, String> params = new HashMap<>();
    params.put("locations", lat + "," + lng);
    // Here you can put another params if needed

    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = jsonParser.makeHttpRequest(URL, METHOD, params);

    if(jsonObject != null) {
        Log.d(TAG, jsonObject.toString()); // Check if data has arrived safely?

        try {
            JSONArray results = jsonObject.getJSONArray("results");
            JSONObject result = results.getJSONObject(0);
            elevation = result.getDouble("elevation");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return elevation;
    } else {
        return -1;
    }
}

altitude内拨打doInBackground并查看结果。