Today, in the android project, you need to implement a GPS or network function to obtain the longitude and latitude of the current mobile terminal device. To implement this function, you must use the locationmanager class in the android framework. Next I will directly paste the mainCodeDescribes how to obtain the longitude and latitude of a real-time location through GPS or network.
Private double latitude = 0.0; private double longpolling = 0.0; locationmanager = (locationmanager) getsystemservice (context. location_service); If (locationmanager. isproviderenabled (locationmanager. gps_provider) {location = locationmanager. getlastknownlocation (locationmanager. gps_provider); If (location! = NULL) {latitude = location. getlatitude (); longdistance = location. getlongpolling () ;}} else {locationlistener = new locationlistener () {// trigger this function @ overridepublic void onstatuschanged (string provider, int status, bundle extras) when the provider status is directly switched to available, temporarily unavailable, and no service) {} // This function is triggered when the provider is enabled. For example, if GPS is enabled @ overridepublic void onproviderenabled (string provider) {} // This function is triggered when the provider is disable, for example, if GPS is disabled @ overr Idepublic void onproviderdisabled (string provider) {} // triggers this function when the coordinates change. If the provider transmits the same coordinates, it will not be triggered @ overridepublic void onlocationchanged (location) {If (location! = NULL) {log. E ("map", "location changed: Lat:" + location. getlatitude () + "LNG:" + location. getlongpolling () ;}}; locationmanager. requestlocationupdates (locationmanager. network_provider, 1000, 0, locationlistener); location = locationmanager. getlastknownlocation (locationmanager. network_provider); If (location! = NULL) {latitude = location. getlatitude (); // longitude longpolling = location. getlongpolling (); // latitude }}
Do not forget to add the following permissions to the androidmanifest. xml file:
<! -- Internet access permission --> <uses-Permission Android: Name = "android. Permission. Internet"/> <! -- GPS Positioning permission --> <uses-Permission Android: Name = "android. Permission. access_coarse_location"/> <uses-Permission Android: Name = "android. Permission. access_fine_location"/>
Article Source: http://blog.csdn.net/cjjky/article/details/6557561