Android gets the geographic location and analyzes the specific City

Source: Internet
Author: User

Java code
/**
* Get the city name through GPS
*
* @ Param Context
* An activity
* @ Return city name
*/
Public static string getcityname (context ){
Locationmanager;
String contextstring = context. location_service;
Locationmanager = (locationmanager) Context. getsystemservice (contextstring );
Criteria = new criteria ();
Criteria. setaccuracy (criteria. accuracy_fine );
Criteria. setaltituderequired (false );
Criteria. setbearingrequired (false );
Criteria. setcostallowed (false );
Criteria. setpowerrequirement (criteria. power_low );
String cityname = NULL;
// Criteria with the best effect
String provider = locationmanager. getbestprovider (criteria, true );
If (provider = NULL ){
Return NULL;
}
// Obtain coordinate information
Location = locationmanager. getlastknownlocation (provider );
If (location = NULL ){
Return NULL;
}
 
If (location! = NULL ){
Double latitude = location. getlatitude ();
Double longpolling = location. getlongpolling ();
// Determine the encoding in a more geographical environment
Geocoder GC = new geocoder (context, locale. getdefault ());
Try {
// Obtain address-related information \ longitude and latitude
List <address> addresses = GC. getfromlocation (latitude, longpolling, 1 );
Stringbuilder sb = new stringbuilder ();
If (addresses. Size ()> 0 ){
Address = addresses. Get (0 );
SB. append (address. getlocality (). append ("\ n ");
Cityname = sb. tostring ();
}
} Catch (ioexception e ){
}
}
Return cityname;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.