Android Location Service (location-based services)

Source: Internet
Author: User

Android Location service combines GPS positioning, mobile communication, navigation and other technologies to provide comprehensive application services related to spatial location. In recent years, location-based services have grown more rapidly, involving all aspects of business, healthcare, work, and life, providing users with a range of services such as location, tracking, and sensitive area warnings.

The Android platform supports APIs that provide location services, primarily using Locationmanager and Locationproviders objects during the development process.


Used to get the current position, track the device's movement, or set sensitive areas, and the device will issue a specific alert when entering or leaving the sensitive area.


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.

In order for the developed program to provide location services, the first question is how to get locationmanager. get Locationmanager can be obtained by calling the () function, the code is as follows:

StringContext.LOCATION_SERVICE;LocationManager locationManager = (LocationManager) getSystemService(serviceString);

Where Context.location_service indicates access to the location service, the system-level services supported by Android (API 23) are as follows:

static constants for the context class value return Object Description
Location_service Location Locationmanager Update of devices such as control locations
Window_service Window WindowManager Top-level window manager
Layout_inflater_service Layout_inflater Layoutinflater Locationmanager Instantiate an XML resource as a view
Power_service Power PowerManager Power Management


Here I only listed the above four, the other can be viewed in the Android SDK on the public Object Getsystemservice (String name) method, there are 19 system-level services, we do not need to remember all, You can view the SDK documentation when using the appropriate system services. These system services are also used similarly, except that the types of management objects returned differ, and the type of management object They return varies with the name being requested. For example, Context.location_service corresponds to the Locationmanager type object returned, Context.wifi_service corresponds to the Wifimanager type object returned.

Back to our point of this article: LBS (location-based Services), after acquiring Locationmanager, you also need to specify the Locationmanager location method , You can then call the Locationmanager.getlastknowlocation () method to get the current position.

So what are the positioning methods of Locationmanager? In a 2012 published University of Higher learning Android textbook, wrote:

At present, there are two main methods of locating Locationmanager, which are GPS positioning and network location.

Now 2016 years, I do not know 2012 years there are several positioning methods, but I can not have no responsibility to tell you four years ago knowledge. Therefore, the data obtained in the Locationmanager on the GPS positioning, network positioning corresponding static constants are Gps_provider, Network_provider respectively. And provider is the meaning of supply, in order to make it easier to understand, I also suggest that the "positioning method" this way of understanding abandoned, replaced by "Location provider." In addition to the two "location providers" in Locationmanager, there are two other "location providers", namely Passive_provider and Fused_provider.

Locationmanager's location provider has the following four types:

-GPS positioning (Gps_provider)
Using satellites to provide accurate location information requires Android.permissions.ACCESS_FINE_LOCATION user privileges

-Network positioning (Network_provider)
Providing approximate location information using base station or Wi-Fi access depends on the server, which is the ability to translate base station or WIF node information into location information. Permissions Required: Android.permission.ACCESS_COARSE_LOCATION or Android.permission.ACCESS_FINE_LOCATION

-Passive positioning (passive_provider)
A lazy location provider, which is used to receive locations, and does not have access to location information like GPS positioning or network positioning. Borrow a sentence from a document describing it in English: This provider would return locations generated by another providers.

-Fusion Positioning (Fused_provider)
The provider combines the input of all possible location sources to provide the best position fixation. Quote a description in English:

Fused location provider makes things very easy for the developers. The Fused location Provider intelligently manages the underlying location technology and gives your the best location Accor Ding to your needs. It's simple-to-use, the provide immediate location, the power efficient and part of the Google Play Service.

Simply introducing these four location providers, let's choose one to get location information! The code is also very simple:

String provider = LocationManager.GPS_PROVIDER;        Location location = locationManager.getLastKnownLocation(provider);

The Location object obtained above contains information that determines the position, such as longitude, dimension, and speed. The instance code is as follows:

double latitude = location.getLatitude();//维度double longitude = location.getLongitude();//经度

However, in an application that provides location services, it is necessary not only to obtain the current location information, but also to monitor the location changes, which is a matter of listening to a button's Click event. Locationmanager provides a convenient and efficient position monitoring method requestlocationupdate (), which can be set according to the distance of the position and the time interval, and the condition of the position changing time is produced. This avoids the occurrence of a large number of positional change events due to minor distance changes. The code for setting the change of listening position in Locationmanager is as follows:

        locationManager.requestLocationUpdates20000, locationListener);

The first parameter is the location provider, the second parameter is the time interval (in microseconds) at which the position is changed, and the third parameter is the distance condition (m), and the fourth parameter is the callback function, which is used to handle the position change time. The code to implement Locationlistener is as follows:

Private FinalLocationlistener Locationlistener =NewLocationlistener () {@Override         Public void onlocationchanged(Location location) {        }@Override         Public void onstatuschanged(String provider,intStatus, Bundle extras) {}@Override         Public void onproviderenabled(String Provider) {        }@Override         Public void onproviderdisabled(String Provider) {        }    };
    • Onlocationchanged () is called when the position is changed
    • Onstatuschanged () is called when the positioning function hardware status changes
    • Onproviderenabled is called when the user enables the hardware with positioning capability
    • Onproviderdisabled () is called when the user disables the hardware with positioning capability

Finally, the permission to add a response to the Androidmanifest.xml file allows us to use the GPS location function!

If you're still a little vague about the process, take a look at this simple demo:

Interface effect

Send virtual location information to the Android emulator via DDMS:

(Pro-Test genymotion, as native AVD (API22) not available DDMS ... Reason unknown)

The complete code for is as follows:

 PackageCom.example.currentlocationdemo;ImportAndroid. Manifest;ImportAndroid.content.Context;;ImportAndroid.location.Location;ImportAndroid.location.LocationListener;ImportAndroid.location.LocationManager;;;ImportAndroid.os.Bundle;ImportAndroid.widget.TextView; Public  class mainactivity extends appcompatactivity {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);        String servicestring = Context.location_service;        Locationmanager Locationmanager = (locationmanager) getsystemservice (servicestring); String Provider = Locationmanager.gps_provider;if(Activitycompat.checkselfpermission ( This, Manifest.permission.ACCESS_FINE_LOCATION)! = packagemanager.permission_granted && Activitycompat.checkselfpermission ( This, Manifest.permission.ACCESS_COARSE_LOCATION)! = packagemanager.permission_granted) {return;        } Location location = Locationmanager.getlastknownlocation (provider);        Getlocationinfo (location); Locationmanager.requestlocationupdates (provider, -,0, Locationlistener); }Private void Getlocationinfo(Location location)        {String latlonginfo; TextView Locationtext = (TextView) Findviewbyid (;if(Location! =NULL) {DoubleLatitude = Location.getlatitude ();//Dimension            DoubleLongitude = Location.getlongitude ();//LongitudeLatlonginfo ="Dimension:"+ Latitude +"\ n precision:"+ Longitude; }Else{Latlonginfo ="No location found"; } locationtext.settext ("Your Current position is:\n"+ Latlonginfo); }Private FinalLocationlistener Locationlistener =NewLocationlistener () {@Override         Public void onlocationchanged(Location location)        {Getlocationinfo (location); }@Override         Public void onstatuschanged(String provider,intStatus, Bundle extras) {Getlocationinfo (NULL); }@Override         Public void onproviderenabled(String Provider) {Getlocationinfo (NULL); }@Override         Public void onproviderdisabled(String Provider) {        }    };}

Android Location Service (location-based services)

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: 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.