国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android GPS定位詳解

2019-11-09 17:59:44
字體:
供稿:網(wǎng)友

自己項(xiàng)目用到了 ,懶得寫,偶爾發(fā)現(xiàn)這個寫的不錯,就存下來了

一、LocationManager

LocationMangager,位置管理器。要想操作定位相關(guān)設(shè)備,必須先定義個LocationManager。我們可以通過如下代碼創(chuàng)建LocationManger對象。

[java] view plain copy PRint?LocationManger locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);   

 

二、LocationListener

LocationListener,位置監(jiān)聽,監(jiān)聽位置變化,監(jiān)聽設(shè)備開關(guān)與狀態(tài)。

[java] view plain copy print?private LocationListener locationListener=new LocationListener() {                    /**          * 位置信息變化時(shí)觸發(fā)          */          public void onLocationChanged(Location location) {              updateView(location);              Log.i(TAG, "時(shí)間:"+location.getTime());               Log.i(TAG, "經(jīng)度:"+location.getLongitude());               Log.i(TAG, "緯度:"+location.getLatitude());               Log.i(TAG, "海拔:"+location.getAltitude());           }                    /**          * GPS狀態(tài)變化時(shí)觸發(fā)          */          public void onStatusChanged(String provider, int status, Bundle extras) {              switch (status) {              //GPS狀態(tài)為可見時(shí)              case LocationProvider.AVAILABLE:                  Log.i(TAG, "當(dāng)前GPS狀態(tài)為可見狀態(tài)");                  break;              //GPS狀態(tài)為服務(wù)區(qū)外時(shí)              case LocationProvider.OUT_OF_SERVICE:                  Log.i(TAG, "當(dāng)前GPS狀態(tài)為服務(wù)區(qū)外狀態(tài)");                  break;              //GPS狀態(tài)為暫停服務(wù)時(shí)              case LocationProvider.TEMPORARILY_UNAVAILABLE:                  Log.i(TAG, "當(dāng)前GPS狀態(tài)為暫停服務(wù)狀態(tài)");                  break;              }          }                /**          * GPS開啟時(shí)觸發(fā)          */          public void onProviderEnabled(String provider) {              Location location=lm.getLastKnownLocation(provider);              updateView(location);          }                /**          * GPS禁用時(shí)觸發(fā)          */          public void onProviderDisabled(String provider) {              updateView(null);          }      };  

 

三、Location

Location,位置信息,通過Location可以獲取時(shí)間、經(jīng)緯度、海拔等位置信息。上面采用locationListener里面的onLocationChanged()來獲取location,下面講述如何主動獲取location。

[java] view plain copy print?Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);   system.out.println("時(shí)間:"+location.getTime());   system.out.println("經(jīng)度:"+location.getLongitude());    

注意:Location location=new Location(LocationManager.GPS_PROVIDER)方式獲取的location的各個參數(shù)值都是為0。

 

四、GpsStatus.Listener

GpsStatus.Listener ,GPS狀態(tài)監(jiān)聽,包括GPS啟動、停止、第一次定位、衛(wèi)星變化等事件。

[java] view plain copy print?//狀態(tài)監(jiān)聽      GpsStatus.Listener listener = new GpsStatus.Listener() {          public void onGpsStatusChanged(int event) {              switch (event) {              //第一次定位              case GpsStatus.GPS_EVENT_FIRST_FIX:                  Log.i(TAG, "第一次定位");                  break;              //衛(wèi)星狀態(tài)改變              case GpsStatus.GPS_EVENT_SATELLITE_STATUS:                  Log.i(TAG, "衛(wèi)星狀態(tài)改變");                  //獲取當(dāng)前狀態(tài)                  GpsStatus gpsStatus=lm.getGpsStatus(null);                  //獲取衛(wèi)星顆數(shù)的默認(rèn)最大值                  int maxSatellites = gpsStatus.getMaxSatellites();                  //創(chuàng)建一個迭代器保存所有衛(wèi)星                   Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();                  int count = 0;                       while (iters.hasNext() && count <= maxSatellites) {                           GpsSatellite s = iters.next();                           count++;                       }                     System.out.println("搜索到:"+count+"顆衛(wèi)星");                  break;              //定位啟動              case GpsStatus.GPS_EVENT_STARTED:                  Log.i(TAG, "定位啟動");                  break;              //定位結(jié)束              case GpsStatus.GPS_EVENT_STOPPED:                  Log.i(TAG, "定位結(jié)束");                  break;              }          };      };  //綁定監(jiān)聽狀態(tài)  lm.addGpsStatusListener(listener);  

 

五、GpsStatus

GpsStatus,GPS狀態(tài)信息,上面在衛(wèi)星狀態(tài)變化時(shí),我們就用到了GpsStatus。

[java] view plain copy print?//實(shí)例化      GpsStatus gpsStatus = locationManager.getGpsStatus(null); // 獲取當(dāng)前狀態(tài)      //獲取默認(rèn)最大衛(wèi)星數(shù)      int maxSatellites = gpsStatus.getMaxSatellites();       //獲取第一次定位時(shí)間(啟動到第一次定位)      int costTime=gpsStatus.getTimeToFirstFix();     //獲取衛(wèi)星      Iterable<GpsSatellite> iterable=gpsStatus.getSatellites();     //一般再次轉(zhuǎn)換成Iterator      Iterator<GpsSatellite> itrator=iterable.iterator();  

六、GpsSatelliteGpsSatellite,定位衛(wèi)星,包含衛(wèi)星的方位、高度、偽隨機(jī)噪聲碼、信噪比等信息。

[java] view plain copy print?//獲取衛(wèi)星      Iterable<GpsSatellite> iterable=gpsStatus.getSatellites();     //再次轉(zhuǎn)換成Iterator      Iterator<GpsSatellite> itrator=iterable.iterator();     //通過遍歷重新整理為ArrayList      ArrayList<GpsSatellite> satelliteList=new ArrayList<GpsSatellite>();      int count=0;     int maxSatellites=gpsStatus.getMaxSatellites();     while (itrator.hasNext() && count <= maxSatellites) {           GpsSatellite satellite = itrator.next();           satelliteList.add(satellite);           count++;     }      System.out.println("總共搜索到"+count+"顆衛(wèi)星");     //輸出衛(wèi)星信息      for(int i=0;i<satelliteList.size();i++){         //衛(wèi)星的方位角,浮點(diǎn)型數(shù)據(jù)          System.out.println(satelliteList.get(i).getAzimuth());         //衛(wèi)星的高度,浮點(diǎn)型數(shù)據(jù)          System.out.println(satelliteList.get(i).getElevation());         //衛(wèi)星的偽隨機(jī)噪聲碼,整形數(shù)據(jù)          System.out.println(satelliteList.get(i).getPrn());         //衛(wèi)星的信噪比,浮點(diǎn)型數(shù)據(jù)          System.out.println(satelliteList.get(i).getSnr());         //衛(wèi)星是否有年歷表,布爾型數(shù)據(jù)          System.out.println(satelliteList.get(i).hasAlmanac());         //衛(wèi)星是否有星歷表,布爾型數(shù)據(jù)          System.out.println(satelliteList.get(i).hasEphemeris());         //衛(wèi)星是否被用于近期的GPS修正計(jì)算          System.out.println(satelliteList.get(i).hasAlmanac());     }  

 

為了便于理解,接下來模擬一個案例,如何在程序代碼中使用GPS獲取位置信息。

第一步:新建一個Android工程項(xiàng)目,命名為mygps,目錄結(jié)構(gòu)如下

 

第二步:修改main.xml布局文件,修改內(nèi)容如下:

[html] view plain copy print?<?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      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"/>  </LinearLayout>  

 

第三步:實(shí)用Adnroid平臺的GPS設(shè)備,需要添加上權(quán)限

[html] view plain copy print?<uses-permission android:name="android.permission.access_FINE_LOCATION"/>      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>  

 

第四步:修改核心組件activity,修改內(nèi)容如下

[java] view plain copy print?package jason.gprs;    import java.util.Iterator;    import android.app.Activity;  import android.content.Context;  import android.content.Intent;  import android.location.Criteria;  import android.location.GpsSatellite;  import android.location.GpsStatus;  import android.location.Location;  import android.location.LocationListener;  import android.location.LocationManager;  import android.location.LocationProvider;  import android.os.Bundle;  import android.provider.Settings;  import android.util.Log;  import android.widget.EditText;  import android.widget.Toast;    public class MainActivity extends Activity {      private EditText editText;      private LocationManager lm;      private static final String TAG = "GpsActivity";        @Override      protected void onDestroy() {          // TODO Auto-generated method stub          super.onDestroy();          lm.removeUpdates(locationListener);      }        @Override      public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);            editText = (EditText) findViewById(R.id.editText);          lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);            // 判斷GPS是否正常啟動          if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {              Toast.makeText(this, "請開啟GPS導(dǎo)航...", Toast.LENGTH_SHORT).show();              // 返回開啟GPS導(dǎo)航設(shè)置界面              Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);              startActivityForResult(intent, 0);              return;          }            // 為獲取地理位置信息時(shí)設(shè)置查詢條件          String bestProvider = lm.getBestProvider(getCriteria(), true);          // 獲取位置信息          // 如果不設(shè)置查詢要求,getLastKnownLocation方法傳人的參數(shù)為LocationManager.GPS_PROVIDER          Location location = lm.getLastKnownLocation(bestProvider);          updateView(location);          // 監(jiān)聽狀態(tài)          lm.addGpsStatusListener(listener);          // 綁定監(jiān)聽,有4個參數(shù)          // 參數(shù)1,設(shè)備:有GPS_PROVIDER和NETWORK_PROVIDER兩種          // 參數(shù)2,位置信息更新周期,單位毫秒          // 參數(shù)3,位置變化最小距離:當(dāng)位置距離變化超過此值時(shí),將更新位置信息          // 參數(shù)4,監(jiān)聽          // 備注:參數(shù)2和3,如果參數(shù)3不為0,則以參數(shù)3為準(zhǔn);參數(shù)3為0,則通過時(shí)間來定時(shí)更新;兩者為0,則隨時(shí)刷新            // 1秒更新一次,或最小位移變化超過1米更新一次;          // 注意:此處更新準(zhǔn)確度非常低,推薦在service里面啟動一個Thread,在run中sleep(10000);然后執(zhí)行handler.sendMessage(),更新位置          lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);      }        // 位置監(jiān)聽      private LocationListener locationListener = new LocationListener() {            /**          * 位置信息變化時(shí)觸發(fā)          */          public void onLocationChanged(Location location) {              updateView(location);              Log.i(TAG, "時(shí)間:" + location.getTime());              Log.i(TAG, "經(jīng)度:" + location.getLongitude());              Log.i(TAG, "緯度:" + location.getLatitude());              Log.i(TAG, "海拔:" + location.getAltitude());          }            /**          * GPS狀態(tài)變化時(shí)觸發(fā)          */          public void onStatusChanged(String provider, int status, Bundle extras) {              switch (status) {              // GPS狀態(tài)為可見時(shí)              case LocationProvider.AVAILABLE:                  Log.i(TAG, "當(dāng)前GPS狀態(tài)為可見狀態(tài)");                  break;              // GPS狀態(tài)為服務(wù)區(qū)外時(shí)              case LocationProvider.OUT_OF_SERVICE:                  Log.i(TAG, "當(dāng)前GPS狀態(tài)為服務(wù)區(qū)外狀態(tài)");                  break;              // GPS狀態(tài)為暫停服務(wù)時(shí)              case LocationProvider.TEMPORARILY_UNAVAILABLE:                  Log.i(TAG, "當(dāng)前GPS狀態(tài)為暫停服務(wù)狀態(tài)");                  break;              }          }            /**          * GPS開啟時(shí)觸發(fā)          */          public void onProviderEnabled(String provider) {              Location location = lm.getLastKnownLocation(provider);              updateView(location);          }            /**          * GPS禁用時(shí)觸發(fā)          */          public void onProviderDisabled(String provider) {              updateView(null);          }        };        // 狀態(tài)監(jiān)聽      GpsStatus.Listener listener = new GpsStatus.Listener() {          public void onGpsStatusChanged(int event) {              switch (event) {              // 第一次定位              case GpsStatus.GPS_EVENT_FIRST_FIX:                  Log.i(TAG, "第一次定位");                  break;              // 衛(wèi)星狀態(tài)改變              case GpsStatus.GPS_EVENT_SATELLITE_STATUS:                  Log.i(TAG, "衛(wèi)星狀態(tài)改變");                  // 獲取當(dāng)前狀態(tài)                  GpsStatus gpsStatus = lm.getGpsStatus(null);                  // 獲取衛(wèi)星顆數(shù)的默認(rèn)最大值                  int maxSatellites = gpsStatus.getMaxSatellites();                  // 創(chuàng)建一個迭代器保存所有衛(wèi)星                  Iterator<GpsSatellite> iters = gpsStatus.getSatellites()                          .iterator();                  int count = 0;                  while (iters.hasNext() && count <= maxSatellites) {                      GpsSatellite s = iters.next();                      count++;                  }                  System.out.println("搜索到:" + count + "顆衛(wèi)星");                  break;              // 定位啟動              case GpsStatus.GPS_EVENT_STARTED:                  Log.i(TAG, "定位啟動");                  break;              // 定位結(jié)束              case GpsStatus.GPS_EVENT_STOPPED:                  Log.i(TAG, "定位結(jié)束");                  break;              }          };      };        /**      * 實(shí)時(shí)更新文本內(nèi)容      *       * @param location      */      private void updateView(Location location) {          if (location != null) {              editText.setText("設(shè)備位置信息/n/n經(jīng)度:");              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();          // 設(shè)置定位精確度 Criteria.ACCURACY_COARSE比較粗略,Criteria.ACCURACY_FINE則比較精細(xì)          criteria.setAccuracy(Criteria.ACCURACY_FINE);          // 設(shè)置是否要求速度          criteria.setSpeedRequired(false);          // 設(shè)置是否允許運(yùn)營商收費(fèi)          criteria.setCostAllowed(false);          // 設(shè)置是否需要方位信息          criteria.setBearingRequired(false);          // 設(shè)置是否需要海拔信息          criteria.setAltitudeRequired(false);          // 設(shè)置對電源的需求          criteria.setPowerRequirement(Criteria.POWER_LOW);          return criteria;      }  }  

第五步:運(yùn)行效果如下,嘿嘿,用的小米3的工程機(jī)做的測試,米3 發(fā)布會吹噓的搜星速度確實(shí)很快:

 

轉(zhuǎn)載:http://blog.csdn.net/jason0539

作者寫的不錯,贊一波


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宝清县| 德格县| 台安县| 蓬安县| 乌拉特前旗| 微博| 延庆县| 鄂伦春自治旗| 遂溪县| 永定县| 杭州市| 泗洪县| 南平市| 临夏县| 海伦市| 大宁县| 侯马市| 高台县| 九龙城区| 深圳市| 潼南县| 襄樊市| 英吉沙县| 绥中县| 新平| 丰镇市| 牙克石市| 邵东县| 兴海县| 光泽县| 广安市| 从江县| 龙井市| 拉萨市| 普宁市| 吉隆县| 内乡县| 喜德县| 乌兰县| 莲花县| 穆棱市|