我有点卡在这里..基本上我试图获取用户的邮政编码位置。我有代码从GPS坐标获得一个ZIP,但我似乎无法获得任何坐标。这是我到目前为止的代码 -Android - 从网络获取位置一次
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线程中的处理程序。
所有我需要的是一个粗略的位置更新(网络位置将是完美的),所以我可以从它那里得到一个邮政编码。
谢谢。
你有没有看着[这](HTTP:// stackoverflow.com/questions/8598910/android-getting-network-gps-location-within-a-short-time-frame-10-seconds-max)? – Kgrover
是上述活动中的代码? –
你说你有Handler的问题,但我没有看到你在paste代码的任何地方使用过处理程序。这是你的所有代码?并且对于邮政编码,您可以使用地理编码器,而不必使用别的东西。 – minhaz