droid gps开发必备资料(含测试demo下载) .

入门资料参考:


 

How accurate is Android GPS? Part 1: Understanding Location Data


Google Developer docs – Location Strategies

Android blog – Deep dive into location

GPS Testing Tool (open source)

HTML5 Geolocation API – How accurate is it, really?



测试demo工程:

GpsActivty.java

  1. public class GpsActivity extends Activity {  
  2.     private EditText editText;  
  3.     private TextView logText;  
  4.     private LocationManager lm;  
  5.     private static final String TAG="GpsActivity";  
  6.      @Override  
  7.      protected void onDestroy() {  
  8.       // TODO Auto-generated method stub   
  9.       super.onDestroy();  
  10.       lm.removeUpdates(locationListener);  
  11.      }  
  12.   
  13.   
  14.  private void setLog(String txt){  
  15.      printTime();  
  16.      setLogInfo(txt);  
  17.  }  
  18.    
  19.  private void setLogInfo(String txt){  
  20.      logText.setText(txt+"\n"+"--------------------\n"+logText.getText());  
  21.  }  
  22.    
  23.  private void printTime(){  
  24.      Calendar ca = Calendar.getInstance();  
  25.      int year = ca.get(Calendar.YEAR);//获取年份   
  26.      int month=ca.get(Calendar.MONTH);//获取月份    
  27.      int day=ca.get(Calendar.DATE);//获取日   
  28.      int minute=ca.get(Calendar.MINUTE);//分    
  29.      int hour=ca.get(Calendar.HOUR);//小时    
  30.      int second=ca.get(Calendar.SECOND);//秒   
  31.      int WeekOfYear = ca.get(Calendar.DAY_OF_WEEK);   
  32.        
  33.        
  34.      setLogInfo("当前日期:" + year +"年"+ month +"月"+ day + "日");  
  35.      setLogInfo(">>>" + hour +"时"+ minute +"分"+ second +"秒");  
  36.  }  
  37.    
  38.     @Override  
  39.     public void onCreate(Bundle savedInstanceState) {  
  40.         super.onCreate(savedInstanceState);  
  41.         setContentView(R.layout.gps_demo);  
  42.           
  43.         editText=(EditText)findViewById(R.id.editText);  
  44.         logText=(TextView) this.findViewById(R.id.logText);  
  45.           
  46.           
  47.         lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);  
  48.           
  49.         //判断GPS是否正常启动   
  50.         if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){  
  51.             Toast.makeText(this"请开启GPS导航...", Toast.LENGTH_SHORT).show();  
  52.             setLog("请开启GPS导航...");  
  53.             //返回开启GPS导航设置界面   
  54.             Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);     
  55.             startActivityForResult(intent,0);   
  56.             return;  
  57.         }  
  58.           
  59.         //为获取地理位置信息时设置查询条件   
  60.         String bestProvider = lm.getBestProvider(getCriteria(), true);  
  61.         //获取位置信息   
  62.         //如果不设置查询要求,getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER   
  63.         Location location= lm.getLastKnownLocation(bestProvider);      
  64.         updateView(location);  
  65.         //监听状态   
  66.         lm.addGpsStatusListener(listener);  
  67.         //绑定监听,有4个参数       
  68.         //参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种   
  69.         //参数2,位置信息更新周期,单位毫秒       
  70.         //参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息       
  71.         //参数4,监听       
  72.         //备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新      
  73.           
  74.         // 1秒更新一次,或最小位移变化超过1米更新一次;   
  75.         //注意:此处更新准确度非常低,推荐在service里面启动一个Thread,在run中sleep(10000);然后执行handler.sendMessage(),更新位置   
  76.         lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10001, locationListener);  
  77.     }  
  78.       
  79.     //位置监听   
  80.     private LocationListener locationListener=new LocationListener() {  
  81.           
  82.         /** 
  83.          * 位置信息变化时触发 
  84.          */  
  85.         public void onLocationChanged(Location location) {  
  86.             updateView(location);  
  87.             Log.i(TAG, "时间:"+location.getTime());   
  88.             Log.i(TAG, "经度:"+location.getLongitude());   
  89.             Log.i(TAG, "纬度:"+location.getLatitude());   
  90.             Log.i(TAG, "海拔:"+location.getAltitude());   
  91.               
  92.               
  93.             setLog( "时间:"+location.getTime());  
  94.             setLog( "经度:"+location.getLongitude());  
  95.             setLog( "纬度:"+location.getLatitude());  
  96.             setLog( "海拔:"+location.getAltitude());  
  97.         }  
  98.           
  99.         /** 
  100.          * GPS状态变化时触发 
  101.          */  
  102.         public void onStatusChanged(String provider, int status, Bundle extras) {  
  103.             switch (status) {  
  104.             //GPS状态为可见时   
  105.             case LocationProvider.AVAILABLE:  
  106.                 Log.i(TAG, "当前GPS状态为可见状态");  
  107.                   
  108.                 setLog("当前GPS状态为可见状态");  
  109.                 break;  
  110.             //GPS状态为服务区外时   
  111.             case LocationProvider.OUT_OF_SERVICE:  
  112.                 Log.i(TAG, "当前GPS状态为服务区外状态");  
  113.                 setLog("当前GPS状态为服务区外状态");  
  114.                 break;  
  115.             //GPS状态为暂停服务时   
  116.             case LocationProvider.TEMPORARILY_UNAVAILABLE:  
  117.                 Log.i(TAG, "当前GPS状态为暂停服务状态");  
  118.                 setLog("当前GPS状态为暂停服务状态");  
  119.                 break;  
  120.             }  
  121.         }  
  122.       
  123.         /** 
  124.          * GPS开启时触发 
  125.          */  
  126.         public void onProviderEnabled(String provider) {  
  127.             Location location=lm.getLastKnownLocation(provider);  
  128.             updateView(location);  
  129.         }  
  130.       
  131.         /** 
  132.          * GPS禁用时触发 
  133.          */  
  134.         public void onProviderDisabled(String provider) {  
  135.             updateView(null);  
  136.         }  
  137.   
  138.       
  139.     };  
  140.       
  141.     //状态监听   
  142.     GpsStatus.Listener listener = new GpsStatus.Listener() {  
  143.         public void onGpsStatusChanged(int event) {  
  144.             switch (event) {  
  145.             //第一次定位   
  146.             case GpsStatus.GPS_EVENT_FIRST_FIX:  
  147.                 Log.i(TAG, "第一次定位");  
  148.                 setLog("第一次定位");  
  149.                 break;  
  150.             //卫星状态改变   
  151.             case GpsStatus.GPS_EVENT_SATELLITE_STATUS:  
  152.                 Log.i(TAG, "卫星状态改变");  
  153.                 setLog("卫星状态改变");  
  154.                 //获取当前状态   
  155.                 GpsStatus gpsStatus=lm.getGpsStatus(null);  
  156.                 //获取卫星颗数的默认最大值   
  157.                 int maxSatellites = gpsStatus.getMaxSatellites();  
  158.                 //创建一个迭代器保存所有卫星    
  159.                 Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();  
  160.                 int count = 0;       
  161.                 while (iters.hasNext() && count <= maxSatellites) {       
  162.                     GpsSatellite s = iters.next();       
  163.                     count++;       
  164.                 }     
  165.                 System.out.println("搜索到:"+count+"颗卫星");  
  166.                 setLog("搜索到:"+count+"颗卫星");  
  167.                 break;  
  168.             //定位启动   
  169.             case GpsStatus.GPS_EVENT_STARTED:  
  170.                 Log.i(TAG, "定位启动");  
  171.                 setLog("定位启动");  
  172.                 break;  
  173.             //定位结束   
  174.             case GpsStatus.GPS_EVENT_STOPPED:  
  175.                 Log.i(TAG, "定位结束");  
  176.                 setLog("定位结束");  
  177.                 break;  
  178.             }  
  179.         };  
  180.     };  
  181.       
  182.     /** 
  183.      * 实时更新文本内容 
  184.      *  
  185.      * @param location 
  186.      */  
  187.     private void updateView(Location location){  
  188.         if(location!=null){  
  189.             editText.setText("设备位置信息\n\n经度:");  
  190.             editText.append(String.valueOf(location.getLongitude()));  
  191.             editText.append("\n纬度:");  
  192.             editText.append(String.valueOf(location.getLatitude()));  
  193.         }else{  
  194.             //清空EditText对象   
  195.             editText.getEditableText().clear();  
  196.         }  
  197.     }  
  198.       
  199.     /** 
  200.      * 返回查询条件 
  201.      * @return 
  202.      */  
  203.     private Criteria getCriteria(){  
  204.         Criteria criteria=new Criteria();  
  205.         //设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细    
  206.         criteria.setAccuracy(Criteria.ACCURACY_FINE);      
  207.         //设置是否要求速度   
  208.         criteria.setSpeedRequired(false);  
  209.         // 设置是否允许运营商收费     
  210.         criteria.setCostAllowed(false);  
  211.         //设置是否需要方位信息   
  212.         criteria.setBearingRequired(false);  
  213.         //设置是否需要海拔信息   
  214.         criteria.setAltitudeRequired(false);  
  215.         // 设置对电源的需求     
  216.         criteria.setPowerRequirement(Criteria.POWER_LOW);  
  217.         return criteria;  
  218.     }  
  219. }  
public class GpsActivity extends Activity {
    private EditText editText;
    private TextView logText;
    private LocationManager lm;
    private static final String TAG="GpsActivity";
	 @Override
	 protected void onDestroy() {
	  // TODO Auto-generated method stub
	  super.onDestroy();
	  lm.removeUpdates(locationListener);
	 }


 private void setLog(String txt){
	 printTime();
	 setLogInfo(txt);
 }
 
 private void setLogInfo(String txt){
	 logText.setText(txt+"\n"+"--------------------\n"+logText.getText());
 }
 
 private void printTime(){
	 Calendar ca = Calendar.getInstance();
     int year = ca.get(Calendar.YEAR);//获取年份
     int month=ca.get(Calendar.MONTH);//获取月份 
     int day=ca.get(Calendar.DATE);//获取日
     int minute=ca.get(Calendar.MINUTE);//分 
     int hour=ca.get(Calendar.HOUR);//小时 
     int second=ca.get(Calendar.SECOND);//秒
     int WeekOfYear = ca.get(Calendar.DAY_OF_WEEK); 
     
     
     setLogInfo("当前日期:" + year +"年"+ month +"月"+ day + "日");
     setLogInfo(">>>" + hour +"时"+ minute +"分"+ second +"秒");
 }
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gps_demo);
        
        editText=(EditText)findViewById(R.id.editText);
        logText=(TextView) this.findViewById(R.id.logText);
        
        
        lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        
        //判断GPS是否正常启动
        if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();
            setLog("请开启GPS导航...");
            //返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);   
            startActivityForResult(intent,0); 
            return;
        }
        
        //为获取地理位置信息时设置查询条件
        String bestProvider = lm.getBestProvider(getCriteria(), true);
        //获取位置信息
        //如果不设置查询要求,getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER
        Location location= lm.getLastKnownLocation(bestProvider);    
        updateView(location);
        //监听状态
        lm.addGpsStatusListener(listener);
        //绑定监听,有4个参数    
        //参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种
        //参数2,位置信息更新周期,单位毫秒    
        //参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息    
        //参数4,监听    
        //备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新   
        
        // 1秒更新一次,或最小位移变化超过1米更新一次;
        //注意:此处更新准确度非常低,推荐在service里面启动一个Thread,在run中sleep(10000);然后执行handler.sendMessage(),更新位置
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
    }
    
    //位置监听
    private LocationListener locationListener=new LocationListener() {
        
        /**
         * 位置信息变化时触发
         */
        public void onLocationChanged(Location location) {
            updateView(location);
            Log.i(TAG, "时间:"+location.getTime()); 
            Log.i(TAG, "经度:"+location.getLongitude()); 
            Log.i(TAG, "纬度:"+location.getLatitude()); 
            Log.i(TAG, "海拔:"+location.getAltitude()); 
            
            
            setLog( "时间:"+location.getTime());
            setLog( "经度:"+location.getLongitude());
            setLog( "纬度:"+location.getLatitude());
            setLog( "海拔:"+location.getAltitude());
        }
        
        /**
         * GPS状态变化时触发
         */
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
            //GPS状态为可见时
            case LocationProvider.AVAILABLE:
                Log.i(TAG, "当前GPS状态为可见状态");
                
                setLog("当前GPS状态为可见状态");
                break;
            //GPS状态为服务区外时
            case LocationProvider.OUT_OF_SERVICE:
                Log.i(TAG, "当前GPS状态为服务区外状态");
                setLog("当前GPS状态为服务区外状态");
                break;
            //GPS状态为暂停服务时
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                Log.i(TAG, "当前GPS状态为暂停服务状态");
                setLog("当前GPS状态为暂停服务状态");
                break;
            }
        }
    
        /**
         * GPS开启时触发
         */
        public void onProviderEnabled(String provider) {
            Location location=lm.getLastKnownLocation(provider);
            updateView(location);
        }
    
        /**
         * GPS禁用时触发
         */
        public void onProviderDisabled(String provider) {
            updateView(null);
        }

    
    };
    
    //状态监听
    GpsStatus.Listener listener = new GpsStatus.Listener() {
        public void onGpsStatusChanged(int event) {
            switch (event) {
            //第一次定位
            case GpsStatus.GPS_EVENT_FIRST_FIX:
                Log.i(TAG, "第一次定位");
                setLog("第一次定位");
                break;
            //卫星状态改变
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                Log.i(TAG, "卫星状态改变");
                setLog("卫星状态改变");
                //获取当前状态
                GpsStatus gpsStatus=lm.getGpsStatus(null);
                //获取卫星颗数的默认最大值
                int maxSatellites = gpsStatus.getMaxSatellites();
                //创建一个迭代器保存所有卫星 
                Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                int count = 0;     
                while (iters.hasNext() && count <= maxSatellites) {     
                    GpsSatellite s = iters.next();     
                    count++;     
                }   
                System.out.println("搜索到:"+count+"颗卫星");
                setLog("搜索到:"+count+"颗卫星");
                break;
            //定位启动
            case GpsStatus.GPS_EVENT_STARTED:
                Log.i(TAG, "定位启动");
                setLog("定位启动");
                break;
            //定位结束
            case GpsStatus.GPS_EVENT_STOPPED:
                Log.i(TAG, "定位结束");
                setLog("定位结束");
                break;
            }
        };
    };
    
    /**
     * 实时更新文本内容
     * 
     * @param location
     */
    private void updateView(Location location){
        if(location!=null){
            editText.setText("设备位置信息\n\n经度:");
            editText.append(String.valueOf(location.getLongitude()));
            editText.append("\n纬度:");
            editText.append(String.valueOf(location.getLatitude()));
        }else{
            //清空EditText对象
            editText.getEditableText().clear();
        }
    }
    
    /**
     * 返回查询条件
     * @return
     */
    private Criteria getCriteria(){
        Criteria criteria=new Criteria();
        //设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细 
        criteria.setAccuracy(Criteria.ACCURACY_FINE);    
        //设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费  
        criteria.setCostAllowed(false);
        //设置是否需要方位信息
        criteria.setBearingRequired(false);
        //设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        // 设置对电源的需求  
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        return criteria;
    }
}

然后在layout目录创建 gps_demo.xml

[javascript] view plain copy print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.     <ScrollView  
  3.         android:layout_width="fill_parent"  
  4.         android:layout_height="fill_parent"  
  5.         xmlns:android="http://schemas.android.com/apk/res/android"  
  6.         >  
  7. <LinearLayout   
  8.     android:orientation="vertical"  
  9.     android:layout_width="fill_parent"  
  10.     android:layout_height="fill_parent">  
  11.     <EditText android:layout_width="fill_parent"  
  12.         android:layout_height="wrap_content"  
  13.         android:cursorVisible="false"  
  14.         android:editable="false"  
  15.         android:id="@+id/editText"/>  
  16.   
  17.    <TextView android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:minHeight="300dp"  
  20.           
  21.         android:id="@+id/logText"/>  
  22.   
  23. </LinearLayout>  
  24.    </ScrollView>  
<?xml version="1.0" encoding="utf-8"?>
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        >
<LinearLayout 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <EditText android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:cursorVisible="false"
        android:editable="false"
        android:id="@+id/editText"/>

   <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minHeight="300dp"
        
        android:id="@+id/logText"/>

</LinearLayout>
   </ScrollView>


最后在AndroidManifest.xml里添加需要的权限

[javascript] view plain copy print ?
  1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>  
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>



手机运行的效果图




注意事项:

1、室内是无法检测到GPS信号的,如果你获得了经纬度,那也是最后一次手机缓存的GPS记录。

2、你获得gps偏移量大的问题,请参照 关于GPS偏移的基础知识

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值