/**
* Obtain the location information.
*/
Private void getlocation (){
// Obtain the Location Management Service
Locationmanager;
String servicename = context. location_service;
Locationmanager = (locationmanager) This. getsystemservice (servicename );
// Find the Service Information
Criteria = new criteria ();
Criteria. setaccuracy (criteria. accuracy_fine); // High Precision
Criteria. setaltituderequired (false );
Criteria. setbearingrequired (false );
Criteria. setcostallowed (true );
Criteria. setpowerrequirement (criteria. power_low); // Low Power Consumption
String provider = locationmanager. getbestprovider (criteria, true); // get GPS information
Location = locationmanager. getlastknownlocation (provider); // obtain the location through GPS
Updatetonewlocation (location );
Try {
Tv1.settext (getlocation (location ));
} Catch (exception e ){
E. printstacktrace ();
Log. E ("", E. getmessage ());
}
}
/**
* Locate the City Based on the accuracy and latitude
*
* @ Param listener
* @ Return
* @ Throws exception
*/
Private string getlocation (location failed) throws exception {
String resultstring = "";
/** Use the get method here to add parameters directly to the URL */
String urlstring = string. Format (
"Http://maps.google.cn/maps/geo? Key = abcdefg & Q = % s, % s ",
Longitude. getlatitude (), longitude. getlongdistance ());
Log. I ("url", urlstring );
/** Create httpclient */
Httpclient client = new defaulthttpclient ();
/** Use the get Method */
Httpget = new httpget (urlstring );
Try {
/** Initiate a GET request and obtain the returned data */
Httpresponse response = client.exe cute (get );
Httpentity entity = response. getentity ();
Bufferedreader buffreader = new bufferedreader (
New inputstreamreader (entity. getcontent ()));
Stringbuffer strbuff = new stringbuffer ();
String result = NULL;
While (result = buffreader. Readline ())! = NULL ){
Strbuff. append (result );
}
Resultstring = strbuff. tostring ();
/** Parse JSON data to obtain the physical address */
If (resultstring! = NULL & resultstring. Length ()> 0 ){
Jsonobject = new jsonobject (resultstring );
Jsonarray = new jsonarray (jsonobject. Get ("placemark ")
. Tostring ());
Resultstring = "";
For (INT I = 0; I <jsonarray. Length (); I ++ ){
Resultstring = jsonarray. getjsonobject (I). getstring (
"Address ");
}
}
} Catch (exception e ){
Throw new exception ("An error occurred while obtaining the physical location:" + E. getmessage ());
} Finally {
Get. Abort ();
Client = NULL;
}
Return resultstring;
}
Add:
In androidmenifest. XML, you must add
Android. Permission. Internet, Android. Permission. access_coarse_location, and Android. Permission. read_phone_state permissions. Otherwise, an error occurs.