Android gets the latitude and longitude data for the current position _android

Source: Internet
Author: User
Tags stub

There is a need to start a service, get the latitude and longitude of the current location, send the captured data to the broadcast, and register the broadcast activity to receive the broadcast information, and will receive the data at the current event, if the current position changes, Latitude and longitude data changes, to obtain changes in latitude and longitude data, through the handler to send messages, update the UI interface, display the updated content, how can I ask such a demo how to achieve?

Locationtool Get Current location information

Android phone to get the current location of the way:GPS positioning, WiFi positioning, base station positioning , the current demo using GPS satellite positioning, in the Locationtool return location, Locationmanager both objects, Through the location provided by the Getlatitude (), getlongitude () read latitude and longitude data, while adding location change listener mylocationlistener, the specific code is as follows:

Package cn.teachcourse.utils; 
Import android.app.Activity; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.location.Criteria; 
Import android.location.Location; 
Import Android.location.LocationListener; 
Import Android.location.LocationManager; 
Import Android.os.Bundle; 
Import android.provider.Settings; 
 
Import Android.widget.Toast; /* @author postmaster@teachcourse.cn @date created in: 2016-1-22 * * public class Locationtool {public Location Getlocat 
  Ion () {return mlocation; 
  public void setlocation (Location Location) {this.mlocation = Location; 
  Private context context; 
  Private Location mlocation; 
 
  Private Locationmanager Mlocationmanager; 
 
    Public Locationtool {super (); 
    Mlocationmanager = (locationmanager) context. Getsystemservice (Context.location_service); 
     
    Mlocation = Mlocationmanager.getlastknownlocation (Getprovider ()); Mlocationmanager.requestlOcationupdates (Locationmanager.gps_provider, the new Mylocationlistener (this)); 
    }//Get location Provider private String Getprovider () {//Build location query Criteria criteria = new criteria (); 
    Query accuracy: High criteria.setaccuracy (Criteria.accuracy_fine); 
    Whether to inquire Sea dial: No criteria.setaltituderequired (false); 
    Whether to query azimuth: no criteria.setbearingrequired (false); 
    Whether to allow payment: is criteria.setcostallowed (true); 
    Electricity Requirements: Low criteria.setpowerrequirement (Criteria.power_low); Returns the most appropriate qualifying provider, and the 2nd argument to true indicates that if only one provider is valid, the current provider return Mlocationmanager.getbestprovider ( 
  criteria, true); 
  Public Locationmanager Getlocationmanager () {return mlocationmanager; Private Locationlistener Mlocationlistener = new Locationlistener () {@Override public void Onstatuscha Nged (String provider, int status, Bundle extras) {//TODO auto-generated method stub} @OverriDe public void onproviderenabled (String provider) {Location L = mlocationmanager.getlastknownlocation (provide 
       
      R); 
      if (l!= null) {mlocation = l; 
    @Override public void onproviderdisabled (String provider) {mlocation = null; @Override public void onlocationchanged (Location Location) {if (Location!= null) {Mlocati 
      on = location; 
 
  } 
 
    } 
  }; public void Closelocation () {if (Mlocationmanager!= null) {if (Mlocationmanager!= null) {Mlocati 
        Onmanager.removeupdates (Mlocationlistener); 
      Mlocationlistener = null; 
    } Mlocationmanager = null; 
 } 
  } 
}

Mylocationlistener Position Change Listener

The Locationmanager object calls Requestlocationupdates (String provider, long mintime, float Mindistance,locationlistener listener Gets the changed location object in the callback's method, where PROVIDER indicates that locationmanager.gps_provider,mintime represents the update location information in the shortest time interval (in milliseconds). Mindistance represents the shortest distance to update location information (per meter), Mylocationlistener inheritance Locationlistener, the following methods need to be overridden:

Package cn.teachcourse.utils; 
Import android.location.Location; 
Import Android.location.LocationListener; 
 
Import Android.os.Bundle; /* @author postmaster@teachcourse.cn @date created in: 2016-1-22 * * public class Mylocationlistener implements Locationli 
 
  Stener {private Locationtool gpstool; 
    /** construction method, incoming Locationtool * @param gpstool * * Public Mylocationlistener (Locationtool Gpstool) {super (); 
  This.gpstool = Gpstool; /** * The current position changes, callback onlocationchanged method, get the changed location object * * * */@Override public void onlocationchanged (Location Location) 
    {if (location!= null) {gpstool.setlocation (location); }/** * When the provider state changes the callback method, the current provider cannot read the location information or provider from the unreadable location information to the method that can read as the information is recalled * */@Overrid 
 
  e public void onstatuschanged (String provider, int status, Bundle extras) {//TODO auto-generated method stub 
  /** * When the provider is allowed to open by the user, the callback onproviderenabled method, such as: Open the positioning function, callback the method * */@Override public void onproviderenabled (String provider) {Location L = Gpstool.getlocationmanager () 
 
    . getlastknownlocation (provider); 
    if (l!= null) {gpstool.setlocation (L); }/** * When provider is not allowed to open, the callback onproviderdisabled method, such as: unable to open the positioning function, callback the method * * */@Override public VO 
 
  ID onproviderdisabled (String provider) {gpstool.setlocation (null); 
 } 
 
}

Locationservice Service Read location information

Why do you have to open the service? Service and activity, fragment also have their own life cycle, Oncreate-->onstartcommand (OnStart)-->onunbind-->onrebind--> OnDestroy, the operation performed in Locationservice is to start a thread to obtain the updated location information and send it as broadcast, with the following specific code:

Package cn.teachcourse.utils; 
Import android.app.Activity; 
Import Android.app.Service; 
Import Android.content.Context; 
Import android.content.Intent; 
Import android.location.Location; 
Import Android.location.LocationManager; 
Import Android.os.IBinder; 
Import android.provider.Settings; 
 
Import Android.widget.Toast; /* @author postmaster@teachcourse.cn @date created in: 2016-1-22 * * public class Locationservice extends Service {Priva 
  Te Locationtool mgpstool = null; 
  Private Boolean threaddisable = false; 
 
  Private final static String TAG = LocationService.class.getSimpleName (); 
    @Override public void OnCreate () {//TODO auto-generated Method Stub super.oncreate (); 
    Mgpstool = new Locationtool (this); 
  Startthread (); 
        private void Startthread () {New Thread (new Runnable () {@Override public void run () { 
          while (!threaddisable) {try {thread.sleep (1000); catch (InterruptedException e) {e.printstacktrace (); } if (Mgpstool!= null) {//When end service GPS is empty//get latitude Location Location = Mgpstool.getloc 
 
            Ation (); 
            Send broadcast Intent Intent = new Intent (); Intent.putextra ("lat", location = null?) 
            "": location.getlatitude () + ""); Intent.putextra ("lon", location = null?) 
            "": location.getlongitude () + ""); 
             
            Intent.setaction ("Cn.teachcourse.utils.GPSService"); 
          Sendbroadcast (Intent); 
  }}}). Start (); 
    @Override public void OnDestroy () {Super.ondestroy (); 
    Threaddisable = true; 
      if (Mgpstool!= null) {mgpstool.closelocation (); 
    Mgpstool = null; 
  @Override public IBinder onbind (Intent Intent) {return null; 
 } 
 
}

Mainactivity start service, register broadcast, display location information

The things that need to be done in Mainactivity are: First start Locationservice service, call StartService () method, second register broadcast receiver (Broadcastreceiver), Creates an internal class Mybroadcastreceiver, inherits Broadcastreceiver, rewrites the OnReceive method, third obtains the latitude and longitude data, updates the UI interface, displays the current position information, the specific code is as follows:

Start the service StartService (this, Locationservice.class) (new Intent); Register broadcast private class Myreceiver extends Broadcastreceiver {@Override public void onreceive 
      Intent Intent) {Bundle Bundle = Intent.getextras (); 
      String lon = bundle.getstring ("Lon"); 
      String lat = bundle.getstring ("lat"); if (! Textutils.isempty (LON) &&! 
        Textutils.isempty (LAT)) {mlatitude = lat; 
        Mlongitude = lon; 
         
        Isobtainloc = true;  New Thread (New Runnable () {@Override public void run () {msg = new 
            Message (); 
          Msg.what = refresh_ui;//Send message, notify Refresh Interface Mhandler.sendmessage (msg); 
      }). Start (); }}//Update UI interface private Handler Mhandler = new Handler () {@Override public void Handlemessage (Me 
      Ssage msg) {//TODO auto-generated Method Stub super.handlemessage (msg); Switch(msg.what) {case Refresh_ui:refreshui (); 
      Break 
      Default:break; 
 
  } 
    } 
  }; private void Refreshui () {if (Isobtainloc) {mtextview.settext ("Longitude Latitude: + mlongitude +" \ n latitudes: + Mlatitud 
      e); 
    Mdialog.dismiss (); 
 } 
 
  }

The above is the entire contents of this article, I hope to learn more about Android software programming help.

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.