Location services, get the current location--locationmanager simple use

Source: Internet
Author: User

Just come into contact with the mobile client features-location services, record simple and effective code.

First get an instance of Locationmanager

// To get an instance of Locationmanager, it is important to note that his instance can only be obtained in the following way, and it is not allowed        to instantiate Locationmanager directly. Locationmanager Locationmanager = (locationmanager) getsystemservice (Context.location_service);

Select a location provider to determine the current location of the device. There are three location providers in Android, Gps_provider (GPS positioning), Network_provider (network positioning) and Passive_provider.

Second, you can get a location object by passing the selected position provider into the Getlastknownlocation () method. If you are not sure which location providers are available, you can use the following method to make a judgment first.

PrivateString provider; //If you are unsure of which location providers are available, you can use the following method to determine. Get all available location providerslist<string> providerlist = Locationmanager.getproviders (true); if(Providerlist.contains (Locationmanager.gps_provider)) {PROVIDER=Locationmanager.gps_provider; } Else if(Providerlist.contains (Locationmanager.network_provider)) {PROVIDER=Locationmanager.network_provider; } Else        {            //popup Toash prompts the user when no location provider is availableToast.maketext ( This, "No location provider", Toast.length_short). Show (); return; }        //access to location objects via providerLocation location = locationmanager.getlastknownlocation (provider);

The above has obtained the location information of the device. When the device location changes to update the information, Loactionmanager provides the Requestlocationupdates () method, passing in a Locationlistener instance.

//after getting the instance of Locationmanager Locatonmanager, we register a periodic location update with the following statementLocationmanager.requestlocationupdates (provider, 5000, 1, Locationlistener); /*The first parameter is the type of the location provider, the code above can be obtained * The second parameter is the time of the listening position change, the number of milliseconds * The third parameter is the distance interval of the listening position change, the unit meter * Fourth three is a listener, need to instantiate L Ocationlistener*/Locationlistener Locationlistener=NewLocationlistener () {@Override Public voidOnstatuschanged (String provider,intstatus, Bundle extras) {            //This function is triggered when the state of the provider is switched directly between available, temporarily unavailable, and service-free states} @Override Public voidonproviderenabled (String provider) {//This function is triggered when the provider is disable, such as when the GPS is closed} @Override Public voidonproviderdisabled (String provider) {//This function is triggered when the provider is enable, such as when the GPS is opened} @Override Public voidonlocationchanged (location location) {//This function is triggered when the coordinates change, and it will not be triggered if the provider is passed into the same coordinates .//Update location information for the current deviceshowlocation (location); }    };

These steps should generally be done in the oncreate () phase of the activity.

After successfully registering a periodic coordinate update, we can get the current coordinates at any time by the following method.

Location location = locationmanager.getlastknownlocation (locationmanager.gps_provider); double latitude = Location.getlatitude ();     // Longitude Double // Latitude double altitude =  location.getaltitude ();     // Altitude

Finally, obtaining a location is required for registration.

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

Here is the entire code, with only one textview in the layout file

 Packagecom.example.locationtest;Importjava.util.List;ImportAndroid.content.Context;Importandroid.location.Location;ImportAndroid.location.LocationListener;ImportAndroid.location.LocationManager;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.view.Window;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsactionbaractivity{PrivateTextView Positontextview; PrivateString provider; PrivateLocationmanager Locationmanager; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Requestwindowfeature (Window.feature_no_title);        Setcontentview (R.layout.activity_main); Positontextview=(TextView) Findviewbyid (R.id.postion_textview); //To get an instance of Locationmanager, it is important to note that his instance can only be obtained in the following way, and it is not allowed to instantiate Locationmanager directly .Locationmanager Locationmanager =(Locationmanager) Getsystemservice (Context.location_service); //If you are unsure of which location providers are available, you can use the following method to determine. Get all available location providerslist<string> providerlist = Locationmanager.getproviders (true); if(Providerlist.contains (Locationmanager.gps_provider)) {PROVIDER=Locationmanager.gps_provider; } Else if(Providerlist.contains (Locationmanager.network_provider)) {PROVIDER=Locationmanager.network_provider; } Else        {            //popup Toash prompts the user when no location provider is availableToast.maketext ( This, "No location provider", Toast.length_short). Show (); return; }        //access to location objects via providerLocation location =locationmanager.getlastknownlocation (provider); if(Location! =NULL)        {            //displays location information for the current deviceshowlocation (location); }        //after getting the instance of Locationmanager Locatonmanager, we register a periodic location update with the following statementLocationmanager.requestlocationupdates (provider, 5000, 1, Locationlistener); /*The first parameter is the type of the location provider, the code above can be obtained * The second parameter is the time of the listening position change, the number of milliseconds * The third parameter is the distance interval of the listening position change, the unit meter * Fourth three is a listener, need to instantiate L Ocationlistener*/} locationlistener Locationlistener=NewLocationlistener () {@Override Public voidOnstatuschanged (String provider,intstatus, Bundle extras) {            //This function is triggered when the state of the provider is switched directly between available, temporarily unavailable, and service-free states} @Override Public voidonproviderenabled (String provider) {//This function is triggered when the provider is disable, such as when the GPS is closed} @Override Public voidonproviderdisabled (String provider) {//This function is triggered when the provider is enable, such as when the GPS is opened} @Override Public voidonlocationchanged (location location) {//This function is triggered when the coordinates change, and it will not be triggered if the provider is passed into the same coordinates .//Update location information for the current deviceshowlocation (location);    }    }; protected voidOnDestroy () {Super. OnDestroy (); if(Locationmanager! =NULL)        {            //Remove the listener when you close the programlocationmanager.removeupdates (Locationlistener); }    }    Private voidshowlocation (location location) {String currentposition= "Latitude is" + location.getlatitude () + "\ n" + "longitude is" +Location.getlongitude ();        System.out.println (currentposition);    Positontextview.settext (currentposition); }}

Location services, get the current location--locationmanager simple use

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.