通過經緯度擷取城市名/地址(不需要三方包),經緯度三方
1:getLocation()方法篩選出最優擷取經緯度的方法
2:MapThread線程通過將getLocation()擷取的經緯度上傳而擷取城市名
public class PositionActivity extends BaseActivity implements IInit, IResponseHandler, View.OnClickListener { private TextView mLocationTV, mCategoryTV;//位置.種類 private double latitude, longitude;//經緯度 private String mapUriStr = "http://maps.google.cn/maps/api/geocode/json?latlng={0},{1}&sensor=true&language=zh-CN"; private HttpResponse httpResponse = null; private HttpEntity httpEntity = null; private MapThread mapThread; private Handler handler; private String result; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_share_goods_edit); init(); } @Override public void init() { mLocationTV = (TextView) findViewById(R.id.tv_goods_location);, getLocation();//擷取經緯度 mapThread = new MapThread(); mapThread.start(); } //擷取經緯度 public void getLocation() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> lp = lm.getAllProviders();// 返回所有已知的位置提供者的名稱列表,包括未獲准訪問或調用活動目前已停用的。 for (String item : lp) {// Log.i("---->可用位置服務:", item); } Criteria criteria = new Criteria(); criteria.setCostAllowed(false);//設定位置服務免費 criteria.setAccuracy(Criteria.ACCURACY_COARSE); //設定水平位置精度 String providerName = lm.getBestProvider(criteria, true); //getBestProvider 只有允許訪問調用活動的位置供應商將被返回 if (providerName != null) { Location location = lm.getLastKnownLocation(providerName); latitude = location.getLatitude();//擷取維度資訊 longitude = location.getLongitude();//擷取經度資訊 } else { ToastUtil.show(this, "1.請檢查網路連接 \n2.請開啟我的位置"); } } class MapThread extends Thread { @Override public void run() { super.run(); String uriStr = MessageFormat.format(mapUriStr, latitude, longitude); HttpGet httpGet = new HttpGet(uriStr);//產生一個請求對象 HttpClient httpClient = new DefaultHttpClient(); //產生一個Http用戶端對象 try { httpResponse = httpClient.execute(httpGet); //使用Http用戶端發送請求對象 httpEntity = httpResponse.getEntity(); //擷取響應內容 BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent())); result = ""; String line = ""; while ((line = reader.readLine()) != null) { result += line; }Log.v("地址:",result ); } catch (Exception e) { e.printStackTrace(); } } }}
擷取城市名摘自這裡