1. 程式人生 > >Android開發之位置定位詳解與例項解析(GPS定位、Google網路定位,BaiduLBS(SDK)定位)

Android開發之位置定位詳解與例項解析(GPS定位、Google網路定位,BaiduLBS(SDK)定位)

複製程式碼
/**
     * 由經緯度獲取所在的城市及區域資訊
     * @author caizhiming
     *
     */
    private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {

        StringBuilder stringBuilder = new StringBuilder();

        @Override
        protected String doInBackground(String... urls) {
            // TODO Auto-generated method stub
            return readJSONFeed(urls[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            String strItem;

            try {

                JSONObject jsonObject = new JSONObject(result);
                JSONObject resultObject = jsonObject.getJSONObject("result");
                JSONObject addressComponentObject = resultObject
                        .getJSONObject("addressComponent");
                String city = addressComponentObject.getString("city");
                String district = addressComponentObject.getString("district");

                city = "城市:" + city;
                district = "    區:" + district;
                stringBuilder.append(city + district);
                textView.setText(stringBuilder.toString());
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
/**
     * 請求json資料
     * @param url
     * @author caizhiming
     */
    public String readJSONFeed(String url) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response;
        try {
            response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } else {
                Log.e("JSON", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }