Android successfully uses GPS to get current geolocation (resolve getlastknownlocation return null)

Source: Internet
Author: User

Recently encountered a tricky problem: using GPS to locate the current location is not available, that is, the Getlastknownlocation method always returns NULL. Later, a blog post getlastknownlocation () returned null resolution helped me a lot, here to thank the blogger, but there are a few things to be aware of, I think it is necessary to add, or read this blog post will still not get the current location.first: When using GPS positioning, it is best not to use the Getlastknownlocation method to get the current position object location, because the object can beThe parameters of the onlocationchanged are given by the system (according to the documentation, Getlastknownlocation has 2 features: 1. Get the current location 2. If the current location is not positioned successfully, you can use this method to get the location of the last time the map was opened in the cache)。 This avoids the null pointer exception. And more importantly, GPS positioning is not able to locate a successful, in more than 90% of the case, Getlastknownlocation returns null second: Locationlistener It is best to instantiate the system's callback method in the activity's OnCreate () method: onlocationchanged (Final location Loc) onproviderdisabled (FINA L string s) onproviderenabled (final string s) onstatuschanged (final string s, Final int i, final Bundle b) Three: Requestlocationupdates must be registered for monitoring in Onresume (). and in OnPause () for anti-registration. Fourth: Test GPS positioning success, go to an empty place to go, do not have shelter. This is very important, otherwise, you never know yourselfWhether GPS positioning is successful. Here is an example of my successful acquisition of the current location using GPS. Hope to help you get rid of the haze of GPs positioning.  @Overridepublic void OnCreate (final Bundle icicle) {      super.oncreate (icicle);       this.setcontentview (R.layout.activity_mapview);        mbtndone = (Button) Findviewbyid (r.id.btn_done);       Mbtndone.setonclicklistener (this);        mapview = (MapView) findViewById ( R.id.map_view);       mapview.setbuiltinzoomcontrols (True);       mapcontroller = Mapview.getcontroller ();       mlocationmanager = ( Locationmanager) Getsystemservice (context.location_service);       mdefaultmarker = Getresources (). getdrawable (R.drawable.map_redpin);      mdefaultmarker.setbounds (0, 0, Mdefaultmarker.getintrinsicwidth (),      mdefaultmarker.getintrinsicheight ());         mbuoyoverlay = new Buoyitemizedoverlay (Mdefaultmarker, this);       INITDENSITYDPI ();       mzoomlevel = Mapview.getmaxzoomlevel ()-1;//  Locationlistener is best instantiated in the activity's OnCreate () method, and when GPs obtains location, it will be self-       Call the Onlocationchanged method.        mlocationlistener = new LocationListener () {            @Override            public void onlocationchanged (final location Loc) {           LOGHELPER.I (TAG, "onlocationchanged. LOC: "+ loc";           if (loc! = null) {    & NBSP;              LOGHELPER.I (TAG, " Onlocationchanged. Latitude: "                             + loc.getlatitude () + ", Longtitude:". Getlongitude ());                    geopoint GeoPoint = Maputils.getgeopoint (loc);                     mapcontroller.animateto (GeoPoint);                    initbuoyoverlayitems (Loc);          } else {             toast (  MapViewActivity.this,  "Your Current location is temporarily unavailable.",                  toast.length_short). Show ();          }      }         //when system setting, location & Security, use wireless networks uncheck, use GPS    & Nbsp;              satellites called when the tick is unchecked        public void onproviderdisabled (final String s) {                  LOGHELPER.I (TAG, " Onproviderdisabled. ");       }                                  //when system setting, location & Security, use wireless networks tick, use GPS satellites tick &NBS p;          Select-Time Call         public void onproviderenabled (final String s) {               LOGHELPER.I (TAG, "onproviderenabled.");         }         public void Onstatuschanged (Final String s, final int i, final Bundle b) {               LOGHELPER.I (TAG, "onstatuschanged.");         }       };      }         @Override         public void OnStart () {            Super.onstart ();              Mapcontroller.setzoom (Mzoomlevel);             if (! DosomegOodutils.isnetworkavailable (this)) {                  mbtndone.setenabled (False);                  showdialog (dialog_no_network);            } else {                  //judge use GPS satellites. Check                   boolean isgpsenabled = Maputils.isgpsprovideravaliable (This);                  //Judging if use wireless networks check                   boolean iswifienabled = maputils.iswifiprovideravaliable ( this);       &NBsp;          if (!isgpsenabled &&!isWIFIEnabled) {                          if not checked, a pop-up dialog box prompts the user to check the selection.                 }                 else {                        location lastknownlocation = null;                       //If just use GPS satellites tick, that means allow GPS positioning                          if (isgpsenabled &&!iswifienabled) {                      lastknownlocation=mlocationmanager.getlastknownlocation (Locationmanager.gps_provider);                        mprovidername = locationmanager.gps_provider;                        //If just use wireless networks tick, Only network targeting is allowed.                       } else if (!isgpsenabled && iswifienabled) {                         Lastknownlocation =    mlocationmanager.getlastknownlocation (Locationmanager.network_provider);                         mprovidername = locationmanager.network_provider;                         //If both are checked, Use GPS as a priority because GPS positioning is more accurate.                      } else if (isgpsenabled && iswifienabled) {              lastknownlocation=mlocationmanager.getlastknownlocation (LocationManager.GPS_ PROVIDER);                    mprovidername = locationmanager.gps_provider;                    if (lastknownlocation = = null) {  & nbsp;          lastknownlocation =mlocationmanager.getlastknownlocation (Locationmanager.network_provider);                mprovidername = locationmanager.network_provider;                    }         }          if (! Textutils.isempty (mprovidername)) {                 mlocationmanager.requestlocationupdates (                      mprovidername, 1000, 1, Mlocationlistener);            }            //ifThe child can locate success, then execute the following code, when using the network positioning, most can be a one-time positioning success, when using GPS, the code will not play a big role.          if (lastknownlocation!) = null) {                Mbtndone.setenabled (True);               Get Current Location              geopoint LastKnownPoint = Getlastknownpoint (lastknownlocation);               //move to this location in an animated way                mapcontroller.animateto (Lastknownpoint);               //update Buoy. This method is not disclosed here. I know what it means.                 Initbuoyoverlayitems (lastknownlocation);          }       }      }      }       @Override       protected Void Onresume () {            super.onresume ();             LOGHELPER.I (TAG, "OnResume. Provider Name: "+ mprovidername);           if (! Textutils.isempty (Mprovidername)) {           //When GPS is located, It is important and necessary to register requestlocationupdates monitoring here. Without this sentence, the positioning cannot succeed.               Mlocationmanager.requestlocationupdates (Mprovidername, 1,        ,            mlocationlistener);            }         }            @Override          protected Void OnPause () {           super.onpause ();            //Unregister monitoring             if (Mlocationmanager! = null) {                mlocationmanager.removeupdates (Mlocationlistener);            }      }}   for positioning methods: some peers, More inclined to use the Getbestprovider method, but I think this way has his drawbacks, not all phones are supported    "use Getbestprovider to get the most suitable location"  , preferably using network positioning and GPS positioning.... Note: Maputils is a tool class source code that I wrote myselfAddress:Http://url.cn/PU7vxq

Android successfully uses GPS to get current geolocation (resolve getlastknownlocation return null)

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.