Android advanced exercise-positioning your app

Source: Internet
Author: User
Tags reverse geocoding
Document directory
  • When you no longer need to locate the service, pay attention to remove the location change listener.
Allows your app to locate users who generally carry their mobile devices with them. A unique feature that can be used for mobile apps is location recognition. When your app has a reasonable application location service, it can bring a better mobile experience to your users. Now we will learn how to add the location service function to your application, learn different ways to obtain user location updates and the best way to use location services. In this chapter, you will learn how to use location service manager to learn what is required before your application can use location management services. some settings to get the current location learn how to use the basic positioning technology on our platform to get the current location of the User display location learn how to make the Location Coordinate information into the user's address information introduction in Android two positioning methods in 1. GPS positioning: built-in to mobile phones (earlier Android phones may not have this module), has become a module of mobile phones, positioning is more accurate 2. Network-based positioning: this positioning method requires mobile phone network, which is divided into base station positioning (WI-FI) and GPRS positioning (mobile phone SIM card ),
Relatively Accurate base station positioning
However, GPRS-based positioning is generally not very accurate. The specific steps in the sample are used to obtain the location manager and determine whether GPS is available. If not, the user is guided to enable GPS.
@ Override protected void onstart () {super. onstart (); // check if the GPS setting is currently enabled on the device. // This verification shocould be done during onstart () because the system CILS this method // when the user returns to the activity, which ensures the desired location provider is // enabled each time the activity resumes from the stopped state. // obtain the location service manager locationmanager locationm Anager = (locationmanager) getsystemservice (context. location_service); // whether the current GPS is available final Boolean gpsenabled = locationmanager. isproviderenabled (locationmanager. gps_provider); If (! Gpsenabled) {// build an alert diert here that requests that the user enable // The location services, then when the user clicks the "OK" button, // call enablelocationsettings () // go to the GPS settings page and ask the user to set new enablegpsdialogfragment (). show (getsuppfrfragmentmanager (), "enablegpsdialog ");}}

Get the GPS or network location instance and register the user location mobile listener

// Set up fine and/or coarse location providers depending on whether the fine provider or // both providers button is pressed. private void setup () {location gpslocation = NULL; location networklocation = NULL; mlocationmanager. removeupdates (listener); mlatlng. settext (R. string. unknown); maddress. settext (R. string. unknown); // get fine location updates only. if (musefine) {mfineproviderbutton. setba Ckgroundresource (R. drawable. button_active); mbothproviderbutton. setbackgroundresource (R. drawable. button_inactive); // request updates from just the fine (GPS) Provider. // obtain the GPS location instance gpslocation = requestupdatesfromprovider (locationmanager. gps_provider, R. string. not_support_gps); // update the UI immediately if a location is obtained. if (gpslocation! = NULL) updateuilocation (gpslocation);} else if (museboth) {// get coarse and fine location updates. mfineproviderbutton. setbackgroundresource (R. drawable. button_inactive); mbothproviderbutton. setbackgroundresource (R. drawable. button_active); // request updates from both fine (GPS) and coarse (network) providers. gpslocation = requestupdatesfromprovider (locationmanager. gps_provider, R. string. not_s Upport_gps); // obtain the network location instance networklocation = requestupdatesfromprovider (locationmanager. network_provider, R. string. not_support_network); // if both providers return last known locations, compare the two and use the better // One to update the UI. if only one provider returns a location, use it. if (gpslocation! = NULL & networklocation! = NULL) {updateuilocation (getbetterlocation (gpslocation, networklocation);} else if (gpslocation! = NULL) {updateuilocation (gpslocation);} else if (networklocation! = NULL) {updateuilocation (networklocation) ;}}/*** method to register location updates with a desired location provider. if the requested * provider is not available on the device, the app displays a toast with a message referenced * by a resource ID. ** @ Param provider name of the requested provider. * @ Param errorresid resource ID for the string message to be displayed if the provider does * not exist on the device. * @ return a previusly returned {@ link android. location. location} from the requested provider, * If exists. * // register the location change listener private location requestupdatesfromprovider (final string provider, final int errorresid) {location = NULL; If (mlocationmanager. isproviderenabled (provider) {// register the listener mlocationmanager. requestlocationupdates (provider, ten_seconds, ten_meters, listener); // The last location information will be saved location = mlocationmanager. getlastknownlocation (provider);} else {toast. maketext (this, errorresid, toast. length_long ). show ();} return location;} // user location change listener private final locationlistener listener = new locationlistener () {@ override public void onlocationchanged (location) {// a new location update is already ed. do something useful with it. update the UI with // The location update. // updateuilocation (location);} @ override public void onproviderdisabled (string provider) {}@ override public void onproviderenabled (string provider) when the location changes) {}@ override public void onstatuschanged (string provider, int status, bundle extras ){}};

Use asynctask to update the UI to enhance user experience

    private void doReverseGeocoding(Location location) {        // Since the geocoding API is synchronous and may take a while.  You don't want to lock        // up the UI thread.  Invoking reverse geocoding in an AsyncTask.        (new ReverseGeocodingTask(this)).execute(new Location[] {location});    }    // AsyncTask encapsulating the reverse-geocoding API.  Since the geocoder API is blocked,    // we do not want to invoke it from the UI thread.    private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {        Context mContext;        public ReverseGeocodingTask(Context context) {            super();            mContext = context;        }        @Override        protected Void doInBackground(Location... params) {            Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());            Location loc = params[0];            List<Address> addresses = null;            try {                addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);            } catch (IOException e) {                e.printStackTrace();                // Update address field with the exception.                Message.obtain(mHandler, UPDATE_ADDRESS, e.toString()).sendToTarget();            }            if (addresses != null && addresses.size() > 0) {                Address address = addresses.get(0);                // Format the first line of address (if available), city, and country name.                String addressText = String.format("%s, %s, %s",                        address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",                        address.getLocality(),                        address.getCountryName());                // Update address field on UI.                Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();            }            return null;        }    }

When you no longer need to locate the service, pay attention to remove the location change listener.

    // Stop receiving location updates whenever the Activity becomes invisible.    @Override    protected void onStop() {        super.onStop();        mLocationManager.removeUpdates(listener);    }
In fact, it is relatively simple to let your app locate, mainly divided into 1. Get the positioning management service, select the appropriate positioning method (GPS positioning is the most accurate, but the positioning time is relatively long, network Positioning is not very accurate, especially in the GPRS network,
Extremely short) 2. register the user location to change the listener, get the user's current location 3. asynchronously update the UI (using asynctask asynchronous class). Finally, you must note that android is required to use the location service. permission. access_fine_location permission sample: http://www.android-doc.com/training/basics/location/index.html #

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.