http://blog.csdn.net/yyywyr/article/details/39063181


 在Android应用程序中,可以使用LocationManager来获取移动设备所在的地理位置信息。看如下实例:新建android应用程序TestLocation。

1、activity_main.xml布局文件

[html] view plain copy print ?
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="fill_parent"  
  3.     android:layout_height="fill_parent"  
  4.     >  
  5.   
  6.     <TextView  
  7.         android:id="@+id/positionView"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         />  
  11.   
  12. LinearLayout>  
    
    用于显示获取到的位置信息。

2、MainActivity.Java

[java] view plain copy print ?
  1. package com.example.testlocation;  
  2.   
  3. import java.util.List;  
  4.   
  5. import android.app.Activity;  
  6. import android.content.Context;  
  7. import android.location.Location;  
  8. import android.location.LocationListener;  
  9. import android.location.LocationManager;  
  10. import android.os.Bundle;  
  11. import android.view.Menu;  
  12. import android.widget.TextView;  
  13. import android.widget.Toast;  
  14.   
  15. public class MainActivity extends Activity {  
  16.       
  17.     private TextView postionView;  
  18.       
  19.     private LocationManager locationManager;  
  20.     private String locationProvider;  
  21.       
  22.     @Override  
  23.     protected void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.activity_main);  
  26.           
  27.         //获取显示地理位置信息的TextView  
  28.         postionView = (TextView) findViewById(R.id.positionView);  
  29.         //获取地理位置管理器  
  30.         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
  31.         //获取所有可用的位置提供器  
  32.         List providers = locationManager.getProviders(true);  
  33.         if(providers.contains(LocationManager.GPS_PROVIDER)){  
  34.             //如果是GPS  
  35.             locationProvider = LocationManager.GPS_PROVIDER;  
  36.         }else if(providers.contains(LocationManager.NETWORK_PROVIDER)){  
  37.             //如果是Network  
  38.             locationProvider = LocationManager.NETWORK_PROVIDER;  
  39.         }else{  
  40.             Toast.makeText(this"没有可用的位置提供器", Toast.LENGTH_SHORT).show();  
  41.             return ;  
  42.         }  
  43.         //获取Location  
  44.         Location location = locationManager.getLastKnownLocation(locationProvider);  
  45.         if(location!=null){  
  46.             //不为空,显示地理位置经纬度  
  47.             showLocation(location);  
  48.         }  
  49.         //监视地理位置变化  
  50.         locationManager.requestLocationUpdates(locationProvider, 30001, locationListener);  
  51.           
  52.     }  
  53.       
  54.     /** 
  55.      * 显示地理位置经度和纬度信息 
  56.      * @param location 
  57.      */  
  58.     private void showLocation(Location location){  
  59.         String locationStr = "维度:" + location.getLatitude() +"\n"   
  60.                 + "经度:" + location.getLongitude();  
  61.         postionView.setText(locationStr);  
  62.     }  
  63.       
  64.     /** 
  65.      * LocationListern监听器 
  66.      * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器 
  67.      */  
  68.       
  69.     LocationListener locationListener =  new LocationListener() {  
  70.           
  71.         @Override  
  72.         public void onStatusChanged(String provider, int status, Bundle arg2) {  
  73.               
  74.         }  
  75.           
  76.         @Override  
  77.         public void onProviderEnabled(String provider) {  
  78.               
  79.         }  
  80.           
  81.         @Override  
  82.         public void onProviderDisabled(String provider) {  
  83.               
  84.         }  
  85.           
  86.         @Override  
  87.         public void onLocationChanged(Location location) {  
  88.             //如果位置发生变化,重新显示  
  89.             showLocation(location);  
  90.               
  91.         }  
  92.     };  
  93.       
  94.     @Override  
  95.     protected void onDestroy() {  
  96.         super.onDestroy();  
  97.         if(locationManager!=null){  
  98.             //移除监听器  
  99.             locationManager.removeUpdates(locationListener);  
  100.         }  
  101.     }  
  102.     @Override  
  103.     public boolean onCreateOptionsMenu(Menu menu) {  
  104.         // Inflate the menu; this adds items to the action bar if it is present.  
  105.         getMenuInflater().inflate(R.menu.main, menu);  
  106.         return true;  
  107.     }  
  108.   
  109. }  
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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//获取显示地理位置信息的TextViewpostionView = (TextView) findViewById(R.id.positionView);//获取地理位置管理器locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);//获取所有可用的位置提供器List providers = locationManager.getProviders(true);if(providers.contains(LocationManager.GPS_PROVIDER)){//如果是GPSlocationProvider = LocationManager.GPS_PROVIDER;}else if(providers.contains(LocationManager.NETWORK_PROVIDER)){//如果是NetworklocationProvider = LocationManager.NETWORK_PROVIDER;}else{Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();return ;}//获取LocationLocation location = locationManager.getLastKnownLocation(locationProvider);if(location!=null){//不为空,显示地理位置经纬度showLocation(location);}//监视地理位置变化locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);}/** * 显示地理位置经度和纬度信息 * @param location */private void showLocation(Location location){String locationStr = "维度:" + location.getLatitude() +"\n" + "经度:" + location.getLongitude();postionView.setText(locationStr);}/** * LocationListern监听器 * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器 */LocationListener locationListener =  new LocationListener() {@Overridepublic void onStatusChanged(String provider, int status, Bundle arg2) {}@Overridepublic void onProviderEnabled(String provider) {}@Overridepublic void onProviderDisabled(String provider) {}@Overridepublic void onLocationChanged(Location location) {//如果位置发生变化,重新显示showLocation(location);}};@Overrideprotected void onDestroy() {super.onDestroy();if(locationManager!=null){//移除监听器locationManager.removeUpdates(locationListener);}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
   从上面可以看出,获取地理位置信息主要分如下步骤:

   (1)获取LocationManager实例,通过getSystemService方法,传入Context.LOCATION_SERVICE参数。

   (2)获取可用的位置提供器,有GPS_PROVIDER、NETWORK_PROVIDER、PASSIVE_PROVIDER三种,前两种比较常用。

   (3)将(2)获取到的位置提供器传入LocationManager的方法getLastKnownLocation,即可获取Location信息。

    如果移动设备地理位置不断发生变化,则实时更新需要进行如下步骤:

   (4)调用LocationManager的requestLocationUpdates方法,第一个参数是位置提供器,第二个参数是监听位置变化的时间间隔(毫秒),第三个参数是监听位置变化的距             离间隔(米),第四个参数是LocationListener监听器

    (5)当位置发生变化后,就会调用监听器的onLocationChanged方法。

    (6)为了省电,节约资源,当程序关闭后,调用LocationManager的removeUpdates方法移除监听器。

3、获取权限

    修改AndroidManifest.xml,添加如下代码:

[html] view plain copy print ?
  1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  
  2.    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
  3.    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>  
  4.    
               
4、效果

   使用模拟器进行测试:点击send

                                                                                                                           

   可以使用Geocoding API查找具体对应的位置。如下:

(1)修改MainActivity.java

[java] view plain copy print ?
  1. package com.example.testlocation;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.client.HttpClient;  
  8. import org.apache.http.client.methods.HttpGet;  
  9. import org.apache.http.impl.client.DefaultHttpClient;  
  10. import org.apache.http.util.EntityUtils;  
  11. import org.json.JSONArray;  
  12. import org.json.JSONObject;  
  13.   
  14. import android.app.Activity;  
  15. import android.content.Context;  
  16. import android.location.Location;  
  17. import android.location.LocationListener;  
  18. import android.location.LocationManager;  
  19. import android.os.Bundle;  
  20. import android.os.Handler;  
  21. import android.os.Message;  
  22. import android.view.Menu;  
  23. import android.widget.TextView;  
  24. import android.widget.Toast;  
  25.   
  26. public class MainActivity extends Activity {  
  27.       
  28.     private TextView postionView;  
  29.       
  30.     private LocationManager locationManager;  
  31.     private String locationProvider;  
  32.       
  33.     public static final int SHOW_LOCATION = 0;  
  34.       
  35.     @Override  
  36.     protected void onCreate(Bundle savedInstanceState) {  
  37.         super.onCreate(savedInstanceState);  
  38.         setContentView(R.layout.activity_main);  
  39.           
  40.         //获取显示地理位置信息的TextView  
  41.         postionView = (TextView) findViewById(R.id.positionView);  
  42.         //获取地理位置管理器  
  43.         locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
  44.         //获取所有可用的位置提供器  
  45.         List providers = locationManager.getProviders(true);  
  46.         if(providers.contains(LocationManager.GPS_PROVIDER)){  
  47.             //如果是GPS  
  48.             locationProvider = LocationManager.GPS_PROVIDER;  
  49.         }else if(providers.contains(LocationManager.NETWORK_PROVIDER)){  
  50.             //如果是Network  
  51.             locationProvider = LocationManager.NETWORK_PROVIDER;  
  52.         }else{  
  53.             Toast.makeText(this"没有可用的位置提供器", Toast.LENGTH_SHORT).show();  
  54.             return ;  
  55.         }  
  56.         //获取Location  
  57.         Location location = locationManager.getLastKnownLocation(locationProvider);  
  58.           
  59.         if(location!=null){  
  60.             //不为空,显示地理位置经纬度  
  61.               
  62.             showLocation(location);  
  63.         }else{  
  64.             Toast.makeText(this"location为空", Toast.LENGTH_SHORT).show();  
  65.         }  
  66.         //监视地理位置变化  
  67.         locationManager.requestLocationUpdates(locationProvider, 30001, locationListener);  
  68.           
  69.     }  
  70.       
  71.     private Handler handler = new Handler(){  
  72.         public void handleMessage(Message msg){  
  73.             switch(msg.what){  
  74.             case SHOW_LOCATION:  
  75.                 String position = (String) msg.obj;  
  76.                 postionView.setText(position);  
  77.                 break;  
  78.             default:  
  79.                 break;  
  80.             }  
  81.         }  
  82.     };  
  83.     /** 
  84.      * 显示地理位置经度和纬度信息 
  85.      * @param location 
  86.      */  
  87.     private void showLocation(final Location location){  
  88.         /*String locationStr = "维度:" + location.getLatitude() +"\n"  
  89.                 + "经度:" + location.getLongitude(); 
  90.         postionView.setText(locationStr);*/  
  91.         new Thread(new Runnable() {  
  92.               
  93.             @Override  
  94.             public void run() {  
  95.                 try{  
  96.                     //组装反向地理编码的接口位置  
  97.                     StringBuilder url = new StringBuilder();  
  98.                     url.append("http://maps.googleapis.com/maps/api/geocode/json?latlng=");  
  99.                     url.append(location.getLatitude()).append(",");  
  100.                     url.append(location.getLongitude());  
  101.                     url.append("&sensor=false");  
  102.                     HttpClient client = new DefaultHttpClient();  
  103.                     HttpGet httpGet = new HttpGet(url.toString());  
  104.                     httpGet.addHeader("Accept-Language","zh-CN");  
  105.                     HttpResponse response = client.execute(httpGet);  
  106.                     if(response.getStatusLine().getStatusCode() == 200){  
  107.                         HttpEntity entity = response.getEntity();  
  108.                         String res = EntityUtils.toString(entity);  
  109.                         //解析  
  110.                         JSONObject jsonObject = new JSONObject(res);  
  111.                         //获取results节点下的位置信息  
  112.                         JSONArray resultArray = jsonObject.getJSONArray("results");  
  113.                         if(resultArray.length() > 0){  
  114.                             JSONObject obj = resultArray.getJSONObject(0);  
  115.                             //取出格式化后的位置数据  
  116.                             String address = obj.getString("formatted_address");  
  117.                               
  118.                             Message msg = new Message();  
  119.                             msg.what = SHOW_LOCATION;  
  120.                             msg.obj = address;  
  121.                             handler.sendMessage(msg);  
  122.                         }  
  123.                     }  
  124.                 }catch(Exception e){  
  125.                     e.printStackTrace();  
  126.                 }  
  127.             }  
  128.         }).start();  
  129.     }  
  130.       
  131.     /** 
  132.      * LocationListern监听器 
  133.      * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器 
  134.      */  
  135.       
  136.     LocationListener locationListener =  new LocationListener() {  
  137.           
  138.         @Override  
  139.         public void onStatusChanged(String provider, int status, Bundle arg2) {  
  140.               
  141.         }  
  142.           
  143.         @Override  
  144.         public void onProviderEnabled(String provider) {  
  145.               
  146.         }  
  147.           
  148.         @Override  
  149.         public void onProviderDisabled(String provider) {  
  150.               
  151.         }  
  152.           
  153.         @Override  
  154.         public void onLocationChanged(Location location) {  
  155.             //如果位置发生变化,重新显示  
  156.             showLocation(location);  
  157.               
  158.         }  
  159.     };  
  160.       
  161.     @Override  
  162.     protected void onDestroy() {  
  163.         super.onDestroy();  
  164.         if(locationManager!=null){  
  165.             //移除监听器  
  166.             locationManager.removeUpdates(locationListener);  
  167.         }  
  168.     }  
  169.     @Override  
  170.     public boolean onCreateOptionsMenu(Menu menu) {  
  171.         // Inflate the menu; this adds items to the action bar if it is present.  
  172.         getMenuInflater().inflate(R.menu.main, menu);  
  173.         return true;  
  174.     }  
  175.   
  176. }  
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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//获取显示地理位置信息的TextViewpostionView = (TextView) findViewById(R.id.positionView);//获取地理位置管理器locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);//获取所有可用的位置提供器List providers = locationManager.getProviders(true);if(providers.contains(LocationManager.GPS_PROVIDER)){//如果是GPSlocationProvider = LocationManager.GPS_PROVIDER;}else if(providers.contains(LocationManager.NETWORK_PROVIDER)){//如果是NetworklocationProvider = LocationManager.NETWORK_PROVIDER;}else{Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();return ;}//获取LocationLocation location = locationManager.getLastKnownLocation(locationProvider);if(location!=null){//不为空,显示地理位置经纬度showLocation(location);}else{Toast.makeText(this, "location为空", Toast.LENGTH_SHORT).show();}//监视地理位置变化locationManager.requestLocationUpdates(locationProvider, 3000, 1, locationListener);}private Handler handler = new Handler(){public void handleMessage(Message msg){switch(msg.what){case SHOW_LOCATION:String position = (String) msg.obj;postionView.setText(position);break;default:break;}}};/** * 显示地理位置经度和纬度信息 * @param location */private void showLocation(final Location location){/*String locationStr = "维度:" + location.getLatitude() +"\n" + "经度:" + location.getLongitude();postionView.setText(locationStr);*/new Thread(new Runnable() {@Overridepublic void run() {try{//组装反向地理编码的接口位置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() == 200){HttpEntity entity = response.getEntity();String res = EntityUtils.toString(entity);//解析JSONObject jsonObject = new JSONObject(res);//获取results节点下的位置信息JSONArray resultArray = jsonObject.getJSONArray("results");if(resultArray.length() > 0){JSONObject obj = resultArray.getJSONObject(0);//取出格式化后的位置数据String address = obj.getString("formatted_address");Message msg = new Message();msg.what = SHOW_LOCATION;msg.obj = address;handler.sendMessage(msg);}}}catch(Exception e){e.printStackTrace();}}}).start();}/** * LocationListern监听器 * 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器 */LocationListener locationListener =  new LocationListener() {@Overridepublic void onStatusChanged(String provider, int status, Bundle arg2) {}@Overridepublic void onProviderEnabled(String provider) {}@Overridepublic void onProviderDisabled(String provider) {}@Overridepublic void onLocationChanged(Location location) {//如果位置发生变化,重新显示showLocation(location);}};@Overrideprotected void onDestroy() {super.onDestroy();if(locationManager!=null){//移除监听器locationManager.removeUpdates(locationListener);}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}
(2)修改AndroidManifest.xml

[html] view plain copy print ?
  1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  
  2.  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />  
  3.  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>  
  4.  <uses-permission android:name="android.permission.INTERNET"/>  
  5.    

更多相关文章

  1. android 悬浮窗教程
  2. Android(安卓)使用模拟位置(支持Android(安卓)6.0)
  3. Android(安卓)API教程:人脸检测(Face Detect)
  4. Android初级教程小案例之单选框RadioGroup与复选框CheckBox
  5. 如何申请 android google map API key
  6. Android移动view动画问题
  7. Android(安卓)更改 Toast 的默认位置及自定义Toast
  8. android locationManager定位
  9. android布局 LinearLayout和RelativeLayout

随机推荐

  1. android中使用开源项目做出上拉、下拉刷
  2. Android中的Toast详解
  3. listview中加入listbutton
  4. Android开发艺术探索-IPC机制
  5. android:excludeFromRecents 属性需要注
  6. Android(安卓)网络通信框架Volley简介(Go
  7. GitHub 优秀的 Android 开源项目和框架
  8. Android 中实现Activity的跳转
  9. Android中Handler的基本使用
  10. Java/Android 中使用Protocol Buffers传