Android gets GPS longitude and latitude

Source: Internet
Author: User

The project needs to complete a small demo without talking nonsense. The Code is as follows:

Public class gpsactivity extends activity {private edittext; private textview TV _gps; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. GPS); edittext = (edittext) findviewbyid (R. id. edittext); TV _gps = (textview) findviewbyid (R. id. textview1); registergps ();} public locationmanager lm; Private Static final string tag = "GPS Serv ICES "; private void registergps () {LM = (locationmanager) getsystemservice (context. location_service); // determine if GPS is enabled normally if (! Lm. isproviderenabled (locationmanager. gps_provider) {toast. maketext (this, "enable GPS navigation... ", toast. length_short ). show (); // return to enable the GPS navigation settings interface intent = new intent (settings. action_location_source_settings); startactivityforresult (intent, 0); return;} // set the query condition string bestprovider = Lm when obtaining geographical location information. getbestprovider (getcriteria (), true); // obtain location information // if no query requirement is set, the parameter of the getlastknownlocation method is locationmanager. gps_pro Vider location = LM. getlastknownlocation (bestprovider); // location = LM. getlastknownlocation (locationmanager. network_provider); updateview (location); // listener lm. addgpsstatuslistener (listener); // bind the listener. There are four parameters // parameter 1, device: gps_provider and network_provider. // parameter 2. The Location Information Update period, unit: millisecond // parameter 3, minimum distance of location change: When the Location Distance changes beyond this value, the location information will be updated // parameter 4, listener // remarks: parameters 2 and 3, if the value of parameter 3 is not 0, parameter 3 prevails. If the value of parameter 3 is 0, the time is used for timed update. If the value of parameter 3 is 0, the system updates the value at any time. // The value is updated once per second, or minimum displacement Update once more than 1 meter; // Note: The update accuracy is very low here. We recommend that you start a thread in the service and sleep (10000) in the run; then execute handler. sendmessage (), update location lm. requestlocationupdates (locationmanager. gps_provider, 1000, 1, locationlistener); // lm. requestlocationupdates (locationmanager. network_provider, 1000, 1, locationlistener);} // location listening private locationlistener = new locationlistener () {/*** triggered when location information changes */Public void onlocationchanged (Lo Cation location) {updateview (location); log. I (TAG, "Time:" + location. gettime (); log. I (TAG, "longitude:" + location. getlongpolling (); log. I (TAG, "latitude:" + location. getlatitude (); log. I (TAG, "altitude:" + location. getaltitude ();}/*** triggered when the GPS status changes */Public void onstatuschanged (string provider, int status, bundle extras) {Switch (Status) {// case locationprovider when the GPS status is visible. available: log. I (TAG, "current GPS status is visible"); break; // Case locationprovider when the GPS status is outside the service area. out_of_service: log. I (TAG, "the current GPS status is out of service"); break; // case locationprovider when the GPS status is suspended. temporarily_unavailable: log. I (TAG, "the current GPS status is suspended"); break ;}/ *** trigger when GPS is enabled */Public void onproviderenabled (string provider) {location = LM. getlastknownlocation (provider); updateview (location);}/*** triggered when GPS is disabled */Public void onproviderdisabled (string provider) {Updateview (null) ;}}; // status listening gpsstatus. listener listener = new gpsstatus. listener () {public void ongpsstatuschanged (INT event) {Switch (event) {// locate case gpsstatus for the first time. gps_event_first_fix: log. I (TAG, "first positioning"); break; // satellite status change case gpsstatus. gps_event_satellite_status: log. I (TAG, ""); // obtain the current gpsstatus = LM. getgpsstatus (null); // gets the default maximum number of satellite stars. Int maxsatellites = gpsstatus. getmax Satellites (); // create an iterator to save all satellite iterator <gpssatellite> iters = gpsstatus. getsatellites (). iterator (); int COUNT = 0; while (iters. hasnext () & count <= maxsatellites) {gpssatellite S = iters. next (); count ++;} system. out. println ("Search:" + Count + ""); TV _gps.settext ("Search:" + Count + ""); break; // locate start case gpsstatus. gps_event_started: log. I (TAG, "locate start"); break; // locate end case gpsstatus. gps_event_stopped: Log. I (TAG, ""); break ;};};/***** update text content in real time ** @ Param location */private void updateview (location) {If (location! = NULL) {edittext. settext ("device location \ n \ N longitude:"); edittext. append (string. valueof (location. getlongdistance (); edittext. append ("\ N latitude:"); edittext. append (string. valueof (location. getlatitude ();} else {// clear edittext object edittext. geteditabletext (). clear () ;}/ ***** return query condition * @ return */private criteria getcriteria () {Criteria = new criteria (); // sets the positioning precision criteria. accuracy_coarse is rough, criteria. accuracy_fine is more precise than criteria. setaccuracy (criteria. accuracy_fine); // sets whether the speed is required for criteria. setspeedrequired (false); // sets whether to allow the carrier to charge criteria. setcostallowed (false); // sets whether the orientation information criteria is required. setbearingrequired (false); // sets whether the elevation information criteria is required. setaltituderequired (false); // sets criteria for power supply. setpowerrequirement (criteria. power_low); return criteria;} @ override protected void ondestroy () {// todo auto-generated method stub super. ondestroy (); lm. removeupdates (locationlistener );}}

Pay attention to the permission added in the androidmainifest. xml file:

<Uses-Permission Android: Name = "android. Permission. access_coarse_location"/>
<Uses-Permission Android: Name = "android. Permission. access_fine_location"/>
<Uses-Permission Android: Name = "android. Permission. access_find_location"/>

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