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

Source: Internet
Author: User



1. Location services, English translation for location-based services, referred to as lbs, also known as location services or position-based services, integration of GPS positioning, mobile communications, navigation and other technologies to provide space-related integrated application services, location-based services are developing rapidly, Covers all aspects of business, healthcare, work and life, providing users with a range of services such as positioning, tracking, and sensitive area warnings. For example, Google Maps, Baidu maps, all need to through location services.


The API for providing location services is supported under the 2.Android platform and is used primarily for Locationmanager and Locationproviders objects during the development process:

(1). The Locationmanager can be used to get the current location, track the device's movement, or set sensitive areas, and the device will issue a specific alert when entering or leaving the sensitive area.

(2). Locationproviders is a collection of components that provide positioning capabilities, each of which provides the current location of the device in different technologies, with the difference in accuracy, speed, and cost of positioning.


3. Next, we will tell you how to achieve the latitude and longitude of the acquisition location, and if the position changes, how to change the location, the latitude also changes the example, here the Locationmanager object as an example:

(1). First, the first step, get the Locationmanager object, can be obtained by calling the Android.app.Activity.getSystemService () function, the code is as follows:

String servicestring = context.location_service;//Gets the location service Locationmanager Locationmanager = (Locationmanager) Getsystemservice (servicestring);//Call the Getsystemservice () method to get the Locationmanager object

The Location_service is an Android-supported system-level service that controls the location of devices such as updates.


(2). After acquiring the Locationmanager object, you also need to specify the location method of the Locationmanager before you can call the Locationmanager.getlastknowlocation () method to get the current position. At present, there are two main methods of locating Locationmanager.

GPS positioning: Can provide more accurate location information, but the location speed and quality is affected by the number of satellites and environmental conditions, need to Android.permissions.ACCESS_FINE_LOCATION user rights.

Network positioning: The location information provided by poor accuracy, but faster than GPS positioning to quickly, using the base station or WiFi access to provide approximate location information, need to have the following permissions: Android.permission.ACCESS_COARSE_LOCATION or Android.permission.ACCESS_FINE_LOCATION.

Note: (Unlike the static constants of the Locationmanager class using GPS positioning and network positioning, the static constants of the Locationmanager class for GPS positioning are: Gps_provider, The static constants of the Locationmanager class for network positioning are: Network_provider, which are used when acquiring the current position. )

To use GPS positioning as an example, get the location information code as follows:

String Provider = locationmanager.gps_provider;//Specifies the positioning method of the Locationmanager location Locationmanager.getlastknownlocation (provider);//Call the Getlastknownlocation () method to get the current location information


(3). By calling the Getlatitude () and Getlonggitude () methods in the location, you can obtain the latitude and longitude in the position information separately, as shown in the following code:

Double lat = location.getlatitude ();//Get latitude double lng = location.getlongitude ();//Get Longitude


(4). In many applications that provide location services, not only do you need to get the current location information, you also need to monitor the location changes and invoke a specific processing method when the location changes, where Locationmanager provides a convenient, Efficient position monitoring Method requestlocationupdates (), can be based on the location of the distance and time interval settings, to create the condition of the position change event, so as to avoid the small distance changes caused by a large number of positional change events, The code for setting the change of listening position in Locationmanager is as follows:

Locationmanager.requestlocationupdates (provider, S, 10,locationlistener);//The conditions for generating position change events are set to a distance of 10 meters, a time interval of 2 seconds, Setting the monitoring position change

Next introduced this line of code of the various parameters, the first parameter is we previously specified Locationmanager positioning method, GPS positioning or network positioning, the second parameter refers to the time interval to generate a position change event, in microseconds, the third parameter refers to the distance condition, in meters, The fourth parameter is a callback function that handles the position change event, which is to set the Locationlistener listener. In general, that line of code sets the conditions for the position change event to 10 meters from the distance, and the interval is 2 seconds.


(5). The code to implement 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, the implementation of the above Locationlistener code of four methods under the simple description:

Onlocationchanged () This method is called when the position is changed, and onproviderdisabled () is called when the user disables the hardware with the positioning function, onproviderenabled () This method is called when the user enables the hardware with positioning capability, and the onstatuschanged () method is called when the hardware state of the positioning function changes, for example, never to get the state of the location information to the state where the location information can be obtained, and vice versa.


(6). In order for the GPS location function to take effect, you also need to add the user license in the Androidmanifest.xml file, that is, add the following line of code, add user rights:

<uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION"/>


4. Next attach the complete code, first create a new Android project, the project name is Locationmanagertest, after the new completed:

(1). Open the Activity_main.xml file for layout, the layout code is as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation= "vertical" >        <textview        android:id= "@+id/location"        android:layout_ Width= "Match_parent"        android:layout_height= "wrap_content"/>    </LinearLayout>

(2). Next open the Mainactivity.java file, through the Locationmanager object to get 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); Setcontentview ( R.layout.activity_main); String servicestring = context.location_service;//Gets the location service Locationmanager Locationmanager = (Locationmanager) Getsystemservice (servicestring);//Call Getsystemservice () method to get locationmanagerstring Provider = Locationmanager.gps_ provider;//Specifies the location of the Locationmanager: Locationmanager.getlastknownlocation (PROVIDER);// Call the Getlastknownlocation () method to get the current position information getlocationinfo (location);// Methods of obtaining latitude and longitude locationmanager.requestlocationupdates (provider, N, 10,locationlistener);//The conditions for generating position change events are set to a distance change of 10 meters, Time interval is 2 seconds, setting the listening position change}private void Getlocationinfo (Location location) {String latlonginfo; TextView Locationtext = (TextView) Findviewbyid (r.id.location);//Gets the TextView component in the layout file if (location = null) {Double lat = l Ocation.getlatitude ();//Get latitude double lng = location.getlongitude ();//Get longitude Latlonginfo = "Latitude:" + lat + "\ n Longitude:" + LNG;} else {latlonginfo = "No current location found";} Locationtext.settext ("Your current position is: \ n" + latlonginfo);//Assign a value for TextView text view}/* * Locationlistener Listener * When the position changes, The latest location information is displayed on the interface */private final Locationlistener locationlistener = new Locationlistener () {@Overridepublic void Onlocat Ionchanged (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 the androidmanifest.xml file is added to the user rights, the code is completed, the Androidmanifest.xml file code is as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/        Android "package=" Xg.locationmanagertest "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" android.p Ermission. Access_fine_location "/> <application android:allowbackup=" true "android:icon=" @drawable/ic_launcher "Android:label=" @string/app_name "android:theme=" @style/apptheme "> <activity Andro Id:name= "xg.locationmanagertest.MainActivity" android:label= "@string/app_name" > <intent-filte r> <action android:name= "Android.intent.action.MAIN"/> <category android:name= " Android.intent.category.LAUNCHER "/> </intent-filter> </activity> </application> </manifest>

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


(4). Location services generally require the use of hardware on the device, the most ideal way to debug is to upload the program to the physical device to run, but in the absence of physical equipment, you can also use the virtual mode provided by the Android simulator to simulate the location of the device changes, debugging the application with location services, Where is the virtual mode device provided by this Android emulator?

Under the Show View menu under the Window menu bar, select the submenu other, pop Up, and select the turn red arrow pointing point to open it:

Open the emulator control in Ddms, enter the current latitude and longitude of the device in the longitude and latitude section of the location controls, and then click the Send button, after opening the Android emulator. The virtual location information is sent to the Android emulator as shown in:




After running this project, click on the Send button, send latitude and longitude to the Android emulator, the effect is as follows:


If we change the longitude to the data, click the Send button:



You will then find that the latitude and longitude in the project have changed, turning into 0 and 0 as entered on our device, as shown in:




5. The above content is only for everyone to love the study reference, this is also I pass the teaching material PPT inside the study, hoped to be useful to everybody, thanks!

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

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.