The latitude and longitude of the location where Android gets

Source: Internet
Author: User

Android provides locationmanager to get location, use Locationlistener to listen for changes in location

Do some initialization work first:

/** latitude and longitude of current location*/public static string mLat = "";p ublic static string Mlon = "",/** Time Out For the GPS location update */private  Timer Mgpstimer = new timer (),/** TimerTask for Time out of the GPS location update */p Rivate  gpstimeouttask mgpstimeouttask = new Gpstimeouttask ();/** GPS location update Time out in Milliseconds*/privat E  Long mgpstimeout = 180000;//3 minutes<span style= "White-space:pre" ></span>public void Initilocationutil (context context, Locationobsever locationobsever) {mlocationobsever = Locationobsever;mcontext = Context;mlocationmanager = (Locationmanager) mcontext.getsystemservice (Context.location_service); Mlocationlistener = new Mylocationlistener ();}


<span style= "White-space:pre" ></span>public void Refreshgps (Boolean calledbycreate) { Mlocationmanager.removeupdates (Mlocationlistener); Boolean providerenable = True;boolean Showlocationservicedisablenotice = true;//See if there is a GPS permission if (mlocationmanager.isproviderenabled (locationmanager.gps_ PROVIDER)) {//start positioning Mlocationlistener as position listener mlocationmanager.requestlocationupdates (Locationmanager.gps_provider , 0, 0, mlocationlistener); showlocationservicedisablenotice = False;//start Time Out timer Mgpstimer = new timer (); Mgpstimeouttask = new Gpstimeouttask (); Mgpstimer.schedule (Mgpstimeouttask, mgpstimeout);} if (mlocationmanager.isproviderenabled (Locationmanager.network_provider)) { Mlocationmanager.requestlocationupdates (locationmanager.network_provider, 0, 0, Mlocationlistener); Showlocationservicedisablenotice = False;providerenable = true;} if (providerenable) {if (mlocationobsever! = null) {Mlocationobsever.notifychange (refreshgps_completed, NULL);}} Else{if (Mlocationobsever! = null) {MLOCATIONOBSEVer.notifychange (Refreshgps_noprovider, NULL);}} if (showlocationservicedisablenotice) {Showlocationservicedisableddialog ();}}


Listener:

Private class Mylocationlistener implements Locationlistener{private Boolean mlocationreceived = false; @Overridepublic void onlocationchanged (location location) {if (location! = null &&!mlocationreceived) {mlocationreceived = true; String lon = string.valueof (Location.getlongitude ()); String lat = string.valueof (Location.getlatitude ()); if (mlocationobsever! = null) {Mlocationobsever.notifychange ( default_location_completed, lat+ "," +lon);}} else if (location = = null) {if (mlocationobsever! = null) {Mlocationobsever.notifychange (getlocation_failed, NULL);}}} @Overridepublic void Onproviderdisabled (String provider) {} @Overridepublic void onproviderenabled (string provider) {}@  overridepublic void Onstatuschanged (String provider, int status,bundle extras) {//TODO auto-generated method stub//if GPS Provider is not accessible, try network Providerif (provider.equals (locationmanager.gps_provider) && Status! = Lo cationprovider.available) {if (mlocationmanager.isproviderenabled (locationmanageR.network_provider)) {mlocationmanager.requestlocationupdates (locationmanager.network_provider, 0, 0, Mlocationlistener);} Else{mlocationmanager.removeupdates (Mlocationlistener); if (mlocationobsever! = null) { Mlocationobsever.notifychange (status_changed, NULL);}}}}


It takes a timer,3 minute to pick up the location again:

Private Handler Mgpstimerhandler = new Handler () {public void Handlemessage (Message msg) {if (Mlocationmanager = = null) {R Eturn;} if (mlocationmanager.isproviderenabled (Locationmanager.network_provider)) {System.out.println ("=====use NETWORK to Get location "); Mlocationmanager.requestlocationupdates (Locationmanager.network_provider, 0, 0,mlocationlistener);} else {mlocationmanager.removeupdates (mlocationlistener);//Mlocationobsever.notifychange ( Setaddlocationbuttonstate_1_setlocationdes_1,null); if (mlocationobsever! = null) {Mlocationobsever.notifychange ( Gpstimeout, NULL);}}};

Switch off the GPS when the interface exits.

/** * Cancel operations of refreshing GPS     */public  void Cancelrefreshgps () {if (Mlocationmanager! = null) { Mlocationmanager.removeupdates (Mlocationlistener);} if (mlocationobsever! = null) {Mlocationobsever.notifychange (cancelgps_completed, NULL);}} Public  void Destroy () {if (Mlocationmanager! = null) {     mlocationmanager.removeupdates (mlocationlistener);} if (Mgpstimer! = null) {Mgpstimer.cancel ();} Cancelrefreshgps (); mcontext = Null;mlocationobsever = null; Mlocationbuildinglist = null; System.GC ();}

Is



When you click on map, assume Google Map, you must use the SDK with the Google API, and then add <uses-library android:name= in Application " Com.google.android.maps "/>

Then the XML is:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" fill_parent "    android:layout_height=" fill_parent "    android:background = "#FFFFFF"    android:gravity= "center_horizontal"    android:orientation= "vertical" >    <include layout= "@layout/title_list"/>    <view        android:id= "@+id/line" android:layout_width= "Fill_parent        "        android:layout_height=" 2dip "        android:layout_below=" @id/title "        android:background=" @drawable/RC _list_divider "/>    <com.google.android.maps.mapview        android:id=" @+id/mapview "        android: Layout_width= "Fill_parent"        android:layout_height= "fill_parent"        android:apikey= "06nx-rzpy8wu16_ GJO8ZBTRYYY-JUNNXNARRXFG "/></linearlayout>

The code is:

@Overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); requestwindowfeature (Window.feature_no_title); Setcontentview (R.LAYOUT.AROUND_MAP); Mtextview = (TextView) Findviewbyid (R.id.title_text); Mtextview.settext ("map"); Intent Intent = Getintent (); mlatitude = Intent.getdoubleextra ("lat", 0.0); mlongitude = Intent.getdoubleextra ("lon", 0.0); Mmapview = (Mapview) Findviewbyid (      R.id.mapview);      Mmapview.setclickable (TRUE);    Mmapview.setbuiltinzoomcontrols (True); Mmapview.setsatellite (true);      Mapcontroller = Mmapview.getcontroller ();//GeoPoint = new GeoPoint ((int) (Mlatitude * 1E6), (int) (Mlongitude * 1E6));    Geopoint=new geoPoint ((int) (30.659259*1000000), (int) (104.065762*1000000));     Mmapview.displayzoomcontrols (TRUE); Sets the initial size of the map. The range is between 1 and 21. 1: Minimum size, 21: Maximum size mapcontroller.setzoom (16);//////Create Myoverlay object for drawing graphics on map Myoverlay myoverlay = new Myoverlay (      ); Mmapview.getoverlays (). Add (myOverlay);  Mapcontroller.animateto (GeoPoint); } @Overrideprotected Boolean isroutedisplayed () {return false;}  Class Myoverlay extends Overlay {@Override public boolean draw (canvas canvas, Mapview Mapview, Boolean shadow,                  Long when) {Paint paint = new paint ();          On-screen text font color paint.setcolor (color.red);                    Point screenpoint = new Point ();          Mapview.getprojection (). Topixels (GeoPoint, screenpoint);          Bitmap bmp = Bitmapfactory.decoderesource (Getresources (), r.drawable.location);          Draw images on the map canvas.drawbitmap (BMP, Screenpoint.x, SCREENPOINT.Y, paint);          Draw the text on the map//Canvas.drawtext ("Mobile Bus", ten, +, paint);      Return Super.draw (canvas, Mapview, Shadow, when);  }  }


The code can be downloaded in http://download.csdn.net/detail/baidu_nod/7622677


The latitude and longitude of the location where Android gets

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.