我很想显示一个包含以下信息的对话框:
我现在不想处理位置更改,只是在对话框中显示这些信息(作为文本)。
但问题是,addresses
变量的大小始终为零。我尝试了两种不同的方式:
AppLocationService appLocationService = new AppLocationService ( HintergrundService.this );
Location location = appLocationService.getLocation ( LocationManager.GPS_PROVIDER );
if (location == null) {
Address adresse = new Address(null);
}
Geocoder gc =new Geocoder(getApplicationContext ());
Address address=null;
List<Address> addresses= null;
try {
addresses = gc.getFromLocation(location.getLatitude(),location.getLongitude(),1);
} catch ( IOException e ) {
e.printStackTrace ();
}
if (addresses.size() > 0) {
address=addresses.get(0);
Toast.makeText ( getApplicationContext (), "" + addresses.get(0).getFeatureName () + "|" + addresses.get ( 0 ).getPostalCode (), Toast.LENGTH_SHORT ).show ();
} else if(addresses.size () <= 0){
Toast.makeText ( getApplicationContext (), "Liste leer", Toast.LENGTH_SHORT ).show ();
}
用这个:
AppLocationService appLocationService = new AppLocationService ( HintergrundService.this );
// Location location = appLocationService.getLocation ( LocationManager.GPS_PROVIDER );
Location location = getLocation ();
double latitude = 0;
double longitude = 0;
if ( location != null ) {
Log.d ( "location", "location " + location + "|" + latitude );
latitude = location.getLatitude ();
longitude = location.getLongitude ();
}
final double finalLatitude = latitude;
final double finalLongitude = longitude;
final String[] result = { null };
//Thread thread = new Thread() {
// @Override
// public void run() {
Geocoder geocoder = new Geocoder ( getApplicationContext (), Locale.getDefault () );
try {
List< Address > addressList = geocoder.getFromLocation (location.getLatitude (), location.getLongitude (), 1 );
Log.d("location1", "location1 " + addressList + "|" + addressList.size () + "|" + geocoder);
if ( addressList != null && addressList.size () > 0 ) {
Address address = addressList.get ( 0 );
StringBuilder sb = new StringBuilder ();
for ( int i = 0 ; i < address.getMaxAddressLineIndex () ; i++ ) {
sb.append ( address.getAddressLine ( i ) ).append ( "\n" );
}
sb.append ( address.getLocality () ).append ( "\n" );
sb.append ( address.getPostalCode () ).append ( "\n" );
sb.append ( address.getCountryName () );
result[ 0 ] = sb.toString ();
Log.d("stringbuilder", "stringbuilder " + sb + "|" + address.getLocality () + "|" + address.getPostalCode () + "|" + address.getCountryName ());
}
} catch ( IOException e ) {
Log.d ( "geocoder", "geocoder", e );
}
Toast.makeText ( HintergrundService.this, "result: " + result[ 0 ], Toast.LENGTH_SHORT ).show ();
addresses
或adressList
变量的大小均为零。
解决:
问题是,Geocoder
对象不适用于Android模拟器。请参阅此帖子:Does the geocoder work on emulators
有一种方法可以测试:Geocoder.isPresent()
。这将使用模拟器返回false
。
当Geocoder.isPresent()
返回false
时,我会使用google api并通过JSON
获取位置:
if (location != null) {
final boolean status = Geocoder.isPresent ();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LocationAddress locationAddress = new LocationAddress();
if(status) {
locationAddress.getAddressFromLocation ( latitude, longitude, getApplicationContext (), handler = new Handler ( Looper.getMainLooper () ) {
@Override
public void handleMessage ( Message message ) {
String locationAddress;
switch ( message.what ) {
case 1:
Bundle bundle = message.getData ();
locationAddress = bundle.getString ( "address" );
break;
default:
locationAddress = null;
}
Log.d ( "locationAdress", "locationAdress " + locationAddress );
}
} );
} else {
final Dialog zeige_gps_daten = new Dialog ( getApplicationContext () );
String currentLocation = LocationAddress.getCurrentLocationViaJSON ( latitude, longitude);
Log.d("currentLocation1", "currentLocation1 " + currentLocation);
String get_location = LocationAddress.get_location ();
String get_street_adress = LocationAddress.get_street_adress ();
String get_postal = LocationAddress.get_postal ();
String get_ortsteil = LocationAddress.get_Ortsteil ();
String get_land = LocationAddress.get_land ();
zeige_gps_daten.getWindow ().setType ( WindowManager.LayoutParams.TYPE_SYSTEM_ALERT );
zeige_gps_daten.setContentView ( R.layout.gps_daten_layout );
TextView straße = (TextView)zeige_gps_daten.findViewById ( R.id.straße_text );
TextView postleitzahl = (TextView)zeige_gps_daten.findViewById ( R.id.postleitzahl_text );
TextView ortsteil = (TextView)zeige_gps_daten.findViewById ( R.id.ortsteil_text );
TextView land = (TextView)zeige_gps_daten.findViewById ( R.id.land_text );
zeige_gps_daten.setTitle ( "aktuelle Position" );
straße.setText ( "Straße: " + get_street_adress ); // passt
postleitzahl.setText ( "Postleitzahl: " + get_postal );
ortsteil.setText ( "Ort: " + get_ortsteil );
land.setText ( "Land: " + get_land );
zeige_gps_daten.show ();
}
}
这称为getCurrentLocationViaJSON()
方法:
public static String getCurrentLocationViaJSON(double lat, double lng) {
JSONObject jsonObj = getLocationInfo ( lat, lng );
Log.i ( "JSON string =>", jsonObj.toString () );
currentLocation = "testing";
street_address = null;
postal_code = null;
ortsteil = null;
land = null;
try {
String status = jsonObj.getString("status").toString();
Log.i("status", status);
if(status.equalsIgnoreCase("OK")){
JSONArray results = jsonObj.getJSONArray("results");
int i = 0;
Log.i("i", i+ "," + results.length() ); //TODO delete this
do{
JSONObject r = results.getJSONObject(i);
JSONArray typesArray = r.getJSONArray("types");
String types = typesArray.getString(0);
if(types.equalsIgnoreCase("street_address")){
street_address = r.getString("formatted_address").split(",")[0];
Log.i("street_address", street_address);
}else if(types.equalsIgnoreCase("postal_code")){
// postal_code = r.getString("formatted_address");
postal_code = r.getString("formatted_address").split ( " " )[0];
ortsteil = r.getString("formatted_address").split ( " " )[1];
land = r.getString("formatted_address").split ( " " )[2];
Log.i("postal_code", postal_code + "|" + ortsteil + "|" + land);
}
if(street_address!=null && postal_code!=null){
currentLocation = street_address + "," + postal_code;
Log.i("Current Location =>", currentLocation); //Delete this
i = results.length();
}
i++;
}while(i<results.length());
Log.i("JSON Geo Locatoin =>", currentLocation);
return currentLocation;
}
} catch (JSONException e) {
Log.e("testing","Failed to load JSON");
e.printStackTrace();
}
return null;
}
你可以看到我用这个分割String(因为postal_code = r.getString("formatted_address");
的原始字符串以这种格式返回一个字符串:('street name''邮政编码''location','country'):< / p>
postal_code = r.getString("formatted_address").split ( " " )[0];
ortsteil = r.getString("formatted_address").split ( " " )[1];
land = r.getString("formatted_address").split ( " " )[2];
getCurrentLocationViaJSON()
方法调用getLocationInfo
方法:
public static JSONObject getLocationInfo(double lat, double lng) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+ lat+","+lng +"&sensor=true");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
重要的是这些行(因为StrictMode$AndroidBlockGuardPolicy.onNetwork
将被抛出):
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);