zoukankan      html  css  js  c++  java
  • 使用LocationManager来获取移动设备所在的地理位置信息

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

    1、activity_main.xml布局文件

    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

    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<String> 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, 3000, 1, locationListener);  
    51.           
    52.     }  
    53.       
    54.     /** 
    55.      * 显示地理位置经度和纬度信息 
    56.      * @param location 
    57.      */  
    58.     private void showLocation(Location location){  
    59.         String locationStr = "维度:" + location.getLatitude() +" "   
    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. }  

       从上面可以看出,获取地理位置信息主要分如下步骤:

       (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,添加如下代码:

    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

    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<String> 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, 3000, 1, 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() +" "  
    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. }  

    (2)修改AndroidManifest.xml

    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.    
  • 相关阅读:
    流行的as3内存释放hack的方法
    干掉这个网页
    Flex元标签笔记Event
    javascript for oop
    asdoc 注释格式
    怎么比较word文档,怎么比较excel文档
    AS3匿名函数的this指向
    SVN空间
    CodeForces 315.D Sereja and Periods
    Html5 filltext
  • 原文地址:https://www.cnblogs.com/yuanzhengang/p/4566324.html
Copyright © 2011-2022 走看看