Android location service Introduction and how to get location information through the LocationManager object

Source: Internet
Author: User

Android location service Introduction and how to get location information through the LocationManager object
Zookeeper

1. location-Based Services (LBS), also known as Location-Based Services, integrates multiple technologies such as GPS positioning, mobile communication, and navigation, it provides comprehensive application services related to spatial locations. Location-Based Services are developing rapidly, involving all aspects of business, medical care, work and life, provides users with a series of services such as location, tracking, and sensitive area warnings. For example, Google Maps and Baidu maps all require location services.

 

2. The Android platform supports location service APIs. during development, the LocationManager and LocationProviders objects are mainly used:

(1) The LocationManager can be used to obtain the current location, track the device's moving route, or set the sensitive area. The device will issue a specific alarm when entering or leaving the sensitive area.

(2). LocationProviders is a set of components that provide the positioning function. Each component in the Set provides the current location of the device with different technologies. The difference lies in the positioning accuracy, speed, and cost.

 

3. Next we will describe how to obtain the longitude and latitude of a location. If the location changes, how to change the location and the latitude and longitude also change. Here we take the LocationManager object as an example:

(1) first, obtain the LocationManager object by calling the android. app. Activity. getSystemService () function. The Code is as follows:

String serviceString = Context. LOCATION_SERVICE; // obtain the location service LocationManager locationManager = (LocationManager) getSystemService (serviceString); // call the getSystemService () method to obtain the LocationManager object

The LOCATION_SERVICE is a system-level service supported by Android, which controls the update of devices such as locations.

 

(2 ). after obtaining the LocationManager object, you must specify the LocationManager locating method before calling the LocationManager. the getLastKnowLocation () method is used to obtain the current location. Currently, LocationManager has two main locating methods.

GPS Positioning: provides more accurate location information, but the positioning speed and quality are affected by the number of satellites and the Environment. android. permissions. ACCESS_FINE_LOCATION is required.

Network Positioning: The accuracy of the provided location information is poor, but the speed is faster than that of GPS positioning. The following permissions are required to provide the approximate location information when accessing the base station or WiFi: android. permission. ACCESS_COARSE_LOCATION or android. permission. ACCESS_FINE_LOCATION.

Note: The static constants of the LocationManager class for GPS Positioning and Network Positioning are different. The static constants of the LocationManager class for GPS positioning are GPS_PROVIDER, and the static constants of the LocationManager class for Network Positioning are NETWORK_PROVIDER, these two static constants are used to obtain the current position .)

The following code uses GPS positioning as an example to obtain the location information:

String provider = LocationManager. GPS_PROVIDER; // Location location = LocationManager. getLastKnownLocation (provider); // call the getLastKnownLocation () method to obtain the current Location information

 

(3) Call the getLatitude () and getLonggitude () methods in Location to obtain the latitude and longitude in the Location information respectively. The Code is as follows:

Double lat = location. getLatitude (); // obtain the latitude. double lng = location. getlongdistance (); // obtain the longitude.

 

(4 ). in many applications that provide the location service, you must not only obtain the current location information, but also monitor location changes and call specific processing methods when the location changes, here, LocationManager provides a convenient and efficient location monitoring method, requestLocationUpdates (), which can be set based on location distance changes and time intervals to generate conditions for location change events, in this way, a large number of location change events are generated due to small distance changes. The code for setting the listening location change in LocationManager is as follows:

LocationManager. requestLocationUpdates (provider, 2000, 10, locationListener); // The condition for generating a location change event is set to a distance of 10 meters, interval of 2 seconds, and listener location change

Next we will introduce the parameters of the above line of code. The first parameter is the positioning method, GPS positioning, or Network Positioning that we previously specified LocationManager, the second parameter refers to the time interval for generating location change events, in microseconds. The third parameter refers to the distance condition, in meters, and the fourth parameter refers to the callback function, it is used to handle location change events, that is, to set the LocationListener listener. In general, the line of code sets the condition for generating a location change event to change the distance by 10 meters and the interval is 2 seconds.

 

(5) The code for implementing locationListener is as follows:

private final LocationListener locationListener = new LocationListener() {@Overridepublic void onLocationChanged(Location location) {// TODO Auto-generated method stub}@Overridepublic void onProviderDisabled(String arg0) {// TODO Auto-generated method stub}@Overridepublic void onProviderEnabled(String arg0) {// TODO Auto-generated method stub}@Overridepublic void onStatusChanged(String arg0, int arg1, Bundle arg2) {// TODO Auto-generated method stub}};


Next, we will give a brief introduction to the four methods in the code that implements LocationListener:

OnLocationChanged () is called when the location changes. onProviderDisabled () is called when the user disables hardware with the location function. onProviderEnabled () this method is called when the user enables hardware with the positioning function. onStatusChanged () is called when the hardware status of the positioning function changes. For example, it never gets the location information from the status to the status where the location information can be obtained, and vice versa.

 

(6) to make the GPS positioning function take effect, you also need to add the user license to the AndroidManifest. xml file, that is, add the following line of code to add the user permission:

 
 

 

4. complete code is attached. First, create an Android project named LocationManagerTest. After the project is created:

(1) Open the activity_main.xml file for layout. The layout code is as follows:

 

         
      
  
 

 

 

(2) Open the MainActivity. java file and use the LocationManager object to obtain the current location. The Code is as follows:

Package xg. locationmanagertest; import android. app. activity; import android. content. context; import android. location. location; import android. location. locationListener; import android. location. locationManager; import android. OS. bundle; import android. widget. textView; public class MainActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); s EtContentView (R. layout. activity_main); String serviceString = Context. LOCATION_SERVICE; // obtain the location service LocationManager locationManager = (LocationManager) getSystemService (serviceString); // call the getSystemService () method to obtain LocationManagerString provider = LocationManager. GPS_PROVIDER; // specifies the LocationManager locating method Location location = locationManager. getLastKnownLocation (provider); // call the getLastKnownLocation () method to obtain the current bit confidence GetLocationInfo (location); // method for obtaining the longitude and latitude: locationManager. requestLocationUpdates (provider, 2000, 10, locationListener); // The condition for generating a location change event is set to a distance of 10 meters and the interval is 2 seconds, set listener Location change} private void getLocationInfo (location Location) {String latLongInfo; TextView locationText = (TextView) findViewById (R. id. location); // obtain the TextView component if (location! = Null) {double lat = location. getLatitude (); // obtain the latitude double lng = location. getlongpolling (); // obtain the longitude latLongInfo = "latitude:" + lat + "\ n longitude:" + lng ;} else {latLongInfo = "no current location found";} locationText. setText ("your current location is \ n" + latLongInfo); // value the TextView.}/** LocationListener listener * When the position changes, the latest Location information is displayed on the Interface */private final LocationListener locationListener = new LocationListener () {@ Overridepublic void onLocationChanged (location Location) {// TODO Auto-generated method stubgetLocationInfo (location) ;}@ Overridepublic void onProviderDisabled (String arg0) {// TODO Auto-generated method stubgetLocationInfo (null );} @ Overridepublic void onProviderEnabled (String arg0) {// TODO Auto-generated method stubgetLocationInfo (null) ;}@ Overridepublic void onStatusChanged (String arg0, int arg1, Bundle arg2) {// TODO Auto-generated method stub }};}



(3). Then add the user permission to the AndroidManifest. xml file, and the code is complete. The AndroidManifest. xml file code is as follows:

 
     
      
                           
                                    
                 
     
                
   
  
 

This completes the code to display the current location information and monitor device location changes.

 

(4 ). generally, the location service uses hardware on the device. The ideal debugging method is to upload the program to the physical device for running, but without the physical device, you can also use the virtual mode provided by the Android simulator to simulate device location changes and debug applications with location services. Where is the virtual mode device provided by the Android simulator?

In the Show View menu under the Window menu bar, select the sub-menu other. In the pop-up Window, open the Red Arrow to open it:

Open the simulator control in DDMS, enable the Android simulator, enter the current Longitude and Latitude of the device in the longpolling and Latitude sections of Location Controls, and then click the Send button, the virtual location information is sent to the Android simulator, as shown in:



 

After running this project, click the send button to send the latitude and longitude to the Android simulator. The effect is as follows:

 

If we change the longitude and latitude to the data, click the send button:


Then we will find that the latitude and longitude of the project have changed to 0 and 0 entered on our device, as shown in:


 

 

5. The above content is only for your reference. This is also learned through the PPT on the teaching materials. I hope it will be useful to you. Thank you!

Related Article

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.