我有点卡在这里..基本上我正在尝试获取用户的邮政编码位置。我有从 GPS 坐标获取 ZIP 的代码,但我似乎无法获取任何坐标。这是我到目前为止的代码 -
Log.d(TAG, "Zip is going to be autoset");
new Thread() {
public void run() {
LocationManager locationManager;
String provider;
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
LocationListener locListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);//true if required
criteria.setBearingRequired(false);//true if required
criteria.setCostAllowed(false);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);//search for enabled provider
//locationManager.requestSingleUpdate(criteria, locListener, null);
Location location= locationManager.getLastKnownLocation(provider);
Log.d(TAG,"Lat - " + (location.getLatitude()) + " long - " + (location.getLongitude()));
latitude = (location.getLatitude());
longitude = (location.getLongitude());
Log.d(TAG, "Passing this link https://maps.googleapis.com/maps/api/geocode/xml?latlng="+latitude+","+longitude+"&sensor=true");
locationManager.removeUpdates(locListener);
try {
//Log.d(TAG, "Trying to access "+ "https://maps.googleapis.com/maps/api/geocode/xml?latlng="+location.getLatitude()+","+location.getLongitude()+"&sensor=true"
//Log.d(TAG, "Trying to access "+ "https://maps.googleapis.com/maps/api/geocode/xml?latlng=40.714224,-73.961452&sensor=true");
URL url = new URL("https://maps.googleapis.com/maps/api/geocode/xml?latlng="+latitude+","+longitude+"&sensor=true");
InputStream stream = url.openStream();
BufferedInputStream buf = new BufferedInputStream(stream);
StringBuilder sb = new StringBuilder();
while (true){
int data = buf.read();
if (data==-1){
break;
}else{
sb.append((char)data);
}
}
int zipEnd = sb.indexOf("</short_name><type>postal_code");
Log.d(TAG,"ZIP is "+sb.substring(zipEnd-6, zipEnd));
ZipCode = Integer.parseInt(sb.substring(zipEnd-6, zipEnd));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.run();
我收到的最新错误说我无法在尚未调用 looper.prepare 的线程内创建处理程序。
我只需要一次粗略的位置更新(网络位置将是完美的),这样我就可以从中获取邮政编码。
谢谢你。