java - Android getInputStream 无法正常工作

标签 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();
    }

我尝试过类似的问题,但没有成功。

最佳答案

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

您可以使用Asynctask类并将altitude方法移动到doInBackground()内。

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

编辑:

我找到了这个名为 JSONParser 的类,我认为这就是您所需要的,请查看: https://gist.github.com/dmnugent80/b2e22e5546c4b1c391ee

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

您可以通过从 JSONParser 类调用 makeHttpRequest 方法并传递所有需要的参数来修改您的 altitude 方法。如果你做得正确,那么该方法将从 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;
    }
}

doInBackground 中调用 altitude 并查看结果。

关于java - Android getInputStream 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929684/

相关文章:

java - 将日期插入sqllite时将字符串日期转换为long的原因是什么?

java - Gradle-编译多个项目,但未找到共享的项目类

android - 如何升级 Android 应用程序

Java处理数组索引越界

Java : Number of String objects in string pool

java - Android 日历布局

android - 等待计时器不会在按钮单击时重新启动

android - 如何从 android 中的 url 解析多个 JSON 对象和数组?我在那个例子中使用了一个我想要的例子,

android - AsyncTask 从不执行 doInBackground(但在调试时执行)(更新 : Fixed)

android - 没有互联网时应用程序崩溃