Android programming gets the geographical latitude and longitude instance _android

Source: Internet
Author: User
Tags time interval

This article illustrates the latitude and longitude of Android programming to get a location. Share to everyone for your reference, specific as follows:

In the Android application, you can use Locationmanager to get the location information of your mobile device. See the following example: New Android application testlocation.

1. Activity_main.xml Layout file

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
  android:layout_width= "Fill_ Parent "
  android:layout_height=" fill_parent "
  >
  <textview
    android:id=" @+id/positionview "
    android:layout_width= "wrap_content"
    android:layout_height= "wrap_content"
    />
</ Linearlayout>

Used to display the location information obtained.

2, Mainactivity.java

Package com.example.testlocation;
Import java.util.List;
Import android.app.Activity;
Import Android.content.Context;
Import android.location.Location;
Import Android.location.LocationListener;
Import Android.location.LocationManager;
Import Android.os.Bundle;
Import Android.view.Menu;
Import Android.widget.TextView;
Import Android.widget.Toast;
  public class Mainactivity extends activity {private TextView Postionview;
  Private Locationmanager Locationmanager;
  Private String Locationprovider;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Gets the TextView Postionview = (TextView) Findviewbyid (R.id.positionview) that displays the location information;
    Get the location manager Locationmanager = (locationmanager) getsystemservice (Context.location_service);
    Gets all available location providers list<string> providers = Locationmanager.getproviders (true); if (Providers.contains (Locationmanager.gps_provider)) {//ASThe fruit is a GPS locationprovider = Locationmanager.gps_provider; }else if (Providers.contains (Locationmanager.network_provider)) {//if network Locationprovider = LocationManage
    R.network_provider;
      }else{Toast.maketext (This, "No available location provider", Toast.length_short). Show ();
    return;
    //Get Location Location Location = locationmanager.getlastknownlocation (Locationprovider);
    if (location!=null) {//Is not NULL, show geographical latitude and longitude showlocation (location);
  //Monitor geographical changes locationmanager.requestlocationupdates (Locationprovider, 3000, 1, locationlistener); /** * Displays geographical latitude and latitude information * @param location/private void Showlocation (location location) {String Locations
    TR = "Dimension:" + location.getlatitude () + "\ n" + "Longitude:" + location.getlongitude ();
  Postionview.settext (LOCATIONSTR); /** * Locationlistern Listener * Parameters: Geographic provider, time interval for monitoring location changes, distance interval for location changes, Locationlistener listener/Locationlistener Locatio
 Nlistener = new Locationlistener () {   @Override public void onstatuschanged (String provider, int status, Bundle arg2) {} @Override public Vo
    ID onproviderenabled (string provider) {} @Override public void onproviderdisabled (string provider) {}
    @Override public void onlocationchanged (Location Location) {//If the position changes, showlocation (Location) is displayed again;
  }
  };
    @Override protected void OnDestroy () {Super.ondestroy ();
    if (locationmanager!=null) {//Remove listener locationmanager.removeupdates (Locationlistener);  } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds the items to the action
    Bar if it is present.
    Getmenuinflater (). Inflate (R.menu.main, menu);
  return true;

 }
}

As you can see from the above, obtaining geographic information is mainly divided into the following steps:

(1) Get the Locationmanager instance and pass the Context.location_service parameter through the Getsystemservice method.
(2) Obtain the available location providers, there are Gps_provider, Network_provider, passive_provider three kinds, the first two are more commonly used.
(3) The location information can be obtained by passing the location provider (2) to the Locationmanager method getlastknownlocation.
If the location of your mobile device changes constantly, the following steps are required for live updating:
(4) Call the Locationmanager Requestlocationupdates method, the first parameter is the position provider, the second parameter is the interval (milliseconds) at which the listening position changes, and the third parameter is the distance interval (m) at which the listening position changes. The fourth parameter is the Locationlistener listener
(5) When the position is changed, the listener's Onlocationchanged method is invoked.
(6) In order to save power, saving resources, when the program is closed, call Locationmanager Removeupdates method to remove the listener.

3. Get permission

Modify Androidmanifest.xml and add the following code:

<uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android: Name= "Android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name= " Android.permission.ACCESS_COARSE_LOCATION "/>

4, the effect

Test using the simulator: Click Send

You can use the Geocoding API to find specific locations. As follows:

(1) Modify Mainactivity.java

Package com.example.testlocation;
Import java.util.List;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import org.apache.http.client.HttpClient;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.util.EntityUtils;
Import Org.json.JSONArray;
Import Org.json.JSONObject;
Import android.app.Activity;
Import Android.content.Context;
Import android.location.Location;
Import Android.location.LocationListener;
Import Android.location.LocationManager;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.Menu;
Import Android.widget.TextView;
Import Android.widget.Toast;
  public class Mainactivity extends activity {private TextView Postionview;
  Private Locationmanager Locationmanager;
  Private String Locationprovider;
  public static final int show_location = 0; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (Savedinstancestate);
    Setcontentview (R.layout.activity_main);
    Gets the TextView Postionview = (TextView) Findviewbyid (R.id.positionview) that displays the location information;
    Get the location manager Locationmanager = (locationmanager) getsystemservice (Context.location_service);
    Gets all available location providers list<string> providers = Locationmanager.getproviders (true); if (Providers.contains (Locationmanager.gps_provider)) {//if GPS Locationprovider = Locationmanager.gps_provider
    ; }else if (Providers.contains (Locationmanager.network_provider)) {//if network Locationprovider = LocationManage
    R.network_provider;
      }else{Toast.maketext (This, "No available location provider", Toast.length_short). Show ();
    return;
    //Get Location Location Location = locationmanager.getlastknownlocation (Locationprovider);
    if (location!=null) {//Is not NULL, show geographical latitude and longitude showlocation (location);
    }else{Toast.maketext (This, "Location is empty", Toast.length_short). Show (); }//Monitor geographical Change LocaTionmanager.requestlocationupdates (Locationprovider, 3000, 1, locationlistener); Private Handler Handler = new Handler () {public void Handlemessage (msg) {switch (msg.what) {CAs
        E show_location:string position = (String) msg.obj;
        Postionview.settext (position);
      Break
      Default:break;
  }
    }
  }; /** * Displays geographical latitude and latitude information * @param location * * private void Showlocation (final location location) {/*string Locat
    IONSTR = "Dimension:" + location.getlatitude () + "\ n" + "Longitude:" + location.getlongitude (); 
          Postionview.settext (LOCATIONSTR)/New Thread (new Runnable () {@Override public void run () {try{
          Assemble reverse geo-coded interface location StringBuilder URL = new StringBuilder ();
          Url.append ("http://maps.googleapis.com/maps/api/geocode/json?latlng=");
          Url.append (Location.getlatitude ()). Append (",");
          Url.append (Location.getlongitude ()); Url.append ("&Sensor=false ");
          HttpClient client = new Defaulthttpclient ();
          HttpGet httpget = new HttpGet (url.tostring ());
          Httpget.addheader ("Accept-language", "ZH-CN");
          HttpResponse response = Client.execute (HttpGet);
            if (Response.getstatusline (). Getstatuscode () = = httpentity entity = response.getentity ();
            String res = entityutils.tostring (entity);
            Parse Jsonobject jsonobject = new Jsonobject (res);
            Gets the position information under the results node Jsonarray resultarray = Jsonobject.getjsonarray ("results");
              if (resultarray.length () > 0) {jsonobject obj = resultarray.getjsonobject (0);
              Takes out the formatted location data String address = obj.getstring ("formatted_address");
              msg = new Message ();
              Msg.what = show_location;
              Msg.obj = address;
            Handler.sendmessage (msg); }}}catch (Exception e) {e.printstacktrace ();
  }}). Start (); /** * Locationlistern Listener * Parameters: Geographic provider, time interval for monitoring location changes, distance interval for location changes, Locationlistener listener/Locationlistener Locatio Nlistener = new Locationlistener () {@Override public void onstatuschanged (String provider, int status, Bundle arg 2) {} @Override public void onproviderenabled (String provider) {} @Override public void Onprovid Erdisabled (String provider) {} @Override public void onlocationchanged (Location Location) {//If location is changed,
    Re-display showlocation (location);
  }
  };
    @Override protected void OnDestroy () {Super.ondestroy ();
    if (locationmanager!=null) {//Remove listener locationmanager.removeupdates (Locationlistener);  } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds the items to the action
    Bar if it is present.
    Getmenuinflater (). Inflate (R.menu.main, menu);
  return true;

 }
}

(2) Modify Androidmanifest.xml

<uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android: Name= "Android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name= " Android.permission.ACCESS_COARSE_LOCATION "/>
<uses-permission android:name=" Android.permission.INTERNET "/>

I hope this article will help you with the Android program.

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.