There are three kinds of positioning methods, one is GPS, one is through the network, one is based on the base station, but either way, you need to turn on the network or GPS
Add Permissions First
<uses-permission android:name= "Android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission Android:name= "Android.permission.ACCESS_FINE_LOCATION"/>
In the coarse_location is used for base station positioning, without this permission, in the acquisition of Getcelllocation error.
The first way, through Jason, is through the base station, citing the article address: http://www.cnblogs.com/dartagnan/archive/2011/3/9.html, the download is just the code to implement the positioning
/** * For more information on the implementation of Google targeting .<br/> * geolocation, see:<br/> * <a * href= "http://code.google.com/apis/gears/geolocation_network_protocol.html"Mce_href="http://code.google.com/apis/gears/geolocation_network_protocol.html"> *http://code.google.com/apis/gears/geolocation_network_protocol.html</a> */public class Locationact extends Activity {private TextView txtinfo; public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Button btn = (button) Findviewbyid (R.id.btnstart); Txtinfo = (TextView) Findviewbyid (r.id.txtinfo); Btn.setonclicklistener (New Button.onclicklistener () {public void OnClick (view view) {get Location (); } }); } private void GetLocation () {Telephonymanager TM = (Telephonymanager) getsystemservice (context.telephony _service); Gsmcelllocation Gsmcell = (gsmcelllocation) tm.getcelllocation (); int cid = Gsmcell.getcid (); int lac = Gsmcell.getlac (); String netoperator = Tm.getnetworkoperator (); int MCC = integer.valueof (netoperator.substring (0, 3)); int MNC = integer.valueof (netoperator.substring(3, 5)); Jsonobject holder = new Jsonobject (); Jsonarray array = new Jsonarray (); Jsonobject data = new Jsonobject (); try {holder.put ("version", "1.1.0"); Holder.put ("Host", "maps.google.com"); Holder.put ("Address_language", "ZH_CN"); Holder.put ("Request_address", true); Holder.put ("Radio_type", "GSM"); Holder.put ("Carrier", "HTC"); Data.put ("cell_id", CID); Data.put ("Location_area_code", LAC); Data.put ("Mobile_countyr_code", MCC); Data.put ("Mobile_network_code", MNC); Array.put (data); Holder.put ("Cell_towers", array); } catch (Jsonexception e) {e.printstacktrace (); } defaulthttpclient client = new Defaulthttpclient (); HttpPost HttpPost = new HttpPost ("Http://www.google.com/loc/json"); Stringentity stringentity = nulL try {stringentity = new stringentity (holder.tostring ()); } catch (Unsupportedencodingexception e) {e.printstacktrace (); } httppost.setentity (stringentity); HttpResponse HttpResponse = null; try {HttpResponse = Client.execute (HttpPost); } catch (Clientprotocolexception e) {e.printstacktrace (); } catch (IOException e) {e.printstacktrace (); } httpentity httpentity = Httpresponse.getentity (); InputStream is = null; try {is = Httpentity.getcontent (); } catch (IllegalStateException e) {e.printstacktrace (); } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); } InputStreamReader ISR = new InputStreamReader (IS); BufferedReader reader = new BufferedReader (ISR); StringBuffer StringBuffer = new StringBuffer (); try {String result = ""; while (result = Reader.readline ()) = null) {stringbuffer.append (result); }} catch (IOException e) {e.printstacktrace (); } txtinfo.settext (Stringbuffer.tostring ()); } }
The second is to locate by a strict GPS, citing the article address: http://www.cnblogs.com/wisekingokok/archive/2011/09/06/2168479.html, which only references the code
public class Mainactivity extends Activity {private Locationmanager locationmanager; Private Gpsstatus Gpsstatus; @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Gets the Locationmanager object Locationmanager = (Locationmanager) getsystemservice (Location_service); Based on the criteria object you set, get the provider object that most conforms to this standard String Currentprovider = Locationmanager.getprovider (Locationmanager.gps_pro Vider). GetName (); Gets the last position information based on the current provider object location Currentlocation = locationmanager.getlastknownlocation (Currentprovider); If the location information is null, the request updates the location information if (currentlocation = = null) {locationmanager.requestlocationupdates (Currentpro Vider, 0, 0, Locationlistener); }//Add GPS Status Listener Locationmanager.addgpsstatuslistener (Gpslistener); Until the last location information is obtained, if the last location information is not obtained, the default latitude/longitude is displayed//Gets the location information once every 10 seconds while (true) {currentlocation = Locationmanager.getlastknownlocation (Currentprovider); if (currentlocation! = null) {LOG.D ("location", "Latitude:" + currentlocation.getlatitude ()); LOG.D ("Location", "Location:" + currentlocation.getlongitude ()); Break }else{log.d ("Location", "Latitude:" + 0); LOG.D ("Location", "Location:" + 0); } try {Thread.Sleep (10000); } catch (Interruptedexception e) {log.e ("location", E.getmessage ()); }}} private Gpsstatus.listener Gpslistener = new Gpsstatus.listener () {//gps state changed when the trigger @Override public void ongpsstatuschanged (int event) {//Gets the current state Gpsstatus=locationmanager . Getgpsstatus (NULL); Switch (event) {//First time location case Gpsstatus.gps_event_first_fix: Break Start locating the event case GpsStatus.GPS_EVENT_STARTED:break; Send GPS satellite Status event case GpsStatus.GPS_EVENT_SATELLITE_STATUS:Toast.makeText (mainactivity.t His, "Gps_event_satellite_status", Toast.length_short). Show (); iterable<gpssatellite> allsatellites = Gpsstatus.getsatellites (); Iterator<gpssatellite> It=allsatellites.iterator (); int count = 0; while (It.hasnext ()) {count++; } toast.maketext (Mainactivity.this, "Satellite count:" + count, Toast.length_short). Show (); Break Stop locating event case GPSSTATUS.GPS_EVENT_STOPPED:LOG.D ("Location", "gps_event_stopped"); Break } } };Create location listener private Locationlistener Locationlistener = new Locationlistener () {//position changed when called @Override public void onlocationchanged (location location) {LOG.D ("location", "onlocationchanged"); }//provider is called @Override public void onproviderdisabled (String provider) {LOG.D (" Location "," onproviderdisabled "); When//provider is enabled, call @Override public void onproviderenabled (String provider) {LOG.D ("L Ocation "," onproviderenabled "); }//The state changes when called @Override public void onstatuschanged (String provider, int status, Bundle extras) { LOG.D ("Location", "onstatuschanged"); } }; }
The third kind is mainly through the network way to locate, the reference article address: http://www.cnblogs.com/wisekingokok/archive/2011/09/05/2167755.html, here only writes the code
Package com.test; Import java.io.IOException; Import java.util.List; Import android.app.Activity; Import android.location.Address; Import Android.location.Criteria; Import Android.location.Geocoder; Import android.location.Location; Import Android.location.LocationListener; Import Android.location.LocationManager; Import Android.os.Bundle; Import Android.util.Log; Import Android.widget.Toast; public class Mainactivity extends Activity {@Override public void onCreate (Bundle savedinstancestate) {su Per.oncreate (savedinstancestate); Setcontentview (R.layout.main); Gets the Locationmanager object Locationmanager Locationmanager = (locationmanager) getsystemservice (LOCATION_SERVICE); Create a criteria criteria = new criteria (); Set the rough Accuracy criteria.setaccuracy (criteria.accuracy_coarse); Sets whether to return elevation information criteria.setaltituderequired (FALSE); Sets whether to return azimuth information criteria.setbearingrequired (false); Sets whether to allow paid service criteria.setcostallowed (true); Set the power consumption level criteria.setpowerrequirement (Criteria.power_high); Sets whether to return speed information criteria.setspeedrequired (false); Gets the provider object that most conforms to this criterion, based on the criteria object Set, String Currentprovider = Locationmanager.getbestprovider (criteria, true); LOG.D ("Location", "Currentprovider:" + currentprovider); Gets the last position information based on the current provider object location Currentlocation = locationmanager.getlastknownlocation (Currentprovider); If the location information is null, the request updates the location information if (currentlocation = = null) {locationmanager.requestlocationupdates (Currentpro Vider, 0, 0, Locationlistener); }//until the last location information is obtained, if the last location information is not obtained, the default latitude/longitude is displayed//Gets the location information once every 10 seconds while (true) {currentlocation = L Ocationmanager.getlastknownlocation (Currentprovider); if (currentlocation! = null) {LOG.D ("location", "Latitude:" + currentlocation.getlatitude ()); LOG.D ("Location"," Location: "+ currentlocation.getlongitude ()); Break }else{log.d ("Location", "Latitude:" + 0); LOG.D ("Location", "Location:" + 0); } try {Thread.Sleep (10000); } catch (Interruptedexception e) {log.e ("location", E.getmessage ()); }}//resolves the address and displays Geocoder Geocoder = new Geocoder (this); try {int latitude = (int) currentlocation.getlatitude (); int longitude = (int) currentlocation.getlongitude (); list<address> list = Geocoder.getfromlocation (latitude, longitude, 2); for (int i=0; i<list.size (); i++) {Address address = list.get (i); Toast.maketext (Mainactivity.this, Address.getcountryname () + address.getadminarea () + address.getfeaturename (), Toast.length_long). Show (); }} catch (IOException e) {Toast.maketexT (Mainactivity.this,e.getmessage (), Toast.length_long). Show (); }}//create location listener private Locationlistener Locationlistener = new Locationlistener () {//Position changed Variable-time call @Override public void onlocationchanged (location location) {LOG.D ("location", "Onlocatio Nchanged "); LOG.D ("Location", "onlocationchanged Latitude" + location.getlatitude ()); LOG.D ("Location", "onlocationchanged location" + location.getlongitude ()); }//provider is called @Override public void onproviderdisabled (String provider) {LOG.D (" Location "," onproviderdisabled "); When//provider is enabled, call @Override public void onproviderenabled (String provider) {LOG.D ("L Ocation "," onproviderenabled "); }//The state changes when called @Override public void onstatuschanged (String provider, int status, Bundle extras) { LOG.D ("Location", "OnstatuschAnged "); } };
Three ways to locate Android