Android GPS初涉
本節引言:
說到GPS這個名詞,相信大家都不陌生,GPS全球定位技術嘛,嗯,Android中定位的方式 一般有這四種:GPS定位,WIFI定準,基地台定位,AGPS定位(基地台+GPS);
本系列教學只講解GPS定位的基本使用! GPS是透過與衛星互動來獲取設備當前的經緯度,準確 度較高,但也有一些缺點,最大的缺點就是:室內幾乎無法使用...需要收到4顆衛星或以上 訊號才能保證GPS的準確定位!但如果你在戶外,無網路的情況,GPS還是可以用的!
本節我們就來探討下Android中的GPS的基本用法~
#1.定位相關的一些API
1 )LocationManager
官方API文件:LocationManager
這玩意是系統服務來的,不能直接new,需要:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
另外用GPS定位別忘了加權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
好的,取得了LocationManager物件後,我們可以呼叫下面這些常用的方法:
- addGpsStatusListener(GpsStatus.Listener listener):新增一個GPS狀態監聽器
- addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent): 新增一個臨界警告
- getAllProviders():取得所有的LocationProvider清單
- getBestProvider(Criteria criteria, boolean enabledOnly):根據指定條件傳回最優LocationProvider
- getGpsStatus(GpsStatus status):取得GPS狀態
- getLastKnownLocation(String provider):根據LocationProvider獲得最近一次已知的Location
- getProvider(String name):根據名稱來取得LocationProvider
- getProviders(boolean enabledOnly):取得所有可用的LocationProvider
- getProviders(Criteria criteria, boolean enabledOnly):根據指定條件取得所有符合條件的LocationProvider
- isProviderEnabled(String provider):判斷指定名稱的LocationProvider是否可用
- removeGpsStatusListener(GpsStatus.Listener listener):刪除GPS狀態監聽器
- removeProximityAlert(PendingIntent intent):刪除一個臨近警告
- #requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntent intent): 透過制定的LocationProvider週期性地取得定位訊息,並透過Intent啟動對應的元件
- requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener): 透過制定的LocationProvider週期性地獲取定位信息,並觸發listener所對應的觸發器
#2)LocationProvider(定位提供者)
#官方API文件:LocationProvider
這比是GPS定位元件的抽象表示,呼叫下述方法可以取得該定位元件的相關資訊!
常用的方法如下:
- getAccuracy():回傳LocationProvider精確度
- getName():傳回LocationProvider名稱
- #getPowerRequirement():取得LocationProvider的電源需求
- hasMonetaryCost():傳回該LocationProvider是收費還是免費的
- meetsCriteria(Criteria criteria) :判斷LocationProvider是否滿足Criteria條件
- requiresCell():判斷LocationProvider是否需要存取網路基地台
- ##requiresNetwork():判斷LocationProvider是否需要存取網路資料
- requiresSatellite():判斷LocationProvider是否需要存取基於衛星的定位系統
- supportsAltitude():判斷LocationProvider是否支援高度訊息
- supportsBearing():判斷LocationProvider是否支援方向資訊
- supportsSpeed():判斷是LocationProvider否支援速度資訊
#3)Location(位置資訊)
官方API文件:位置資訊的抽象類,我們可以呼叫下述方法來獲取相關的定位資訊! 常用方法如下:- float
- getAccuracy():取得定位資訊的精確度 double
- getAltitude( ):取得定位資訊的高度 float
- getBearing():取得定位資訊的方向 double
- getLatitude():取得定位資訊的緯度 double
- getLongitude():取得定位資訊的精確度##String getProvider
- ():取得提供該定位資訊的LocationProvider float getSpeed
- ():取得定位資訊的速度boolean hasAccuracy
- ():判斷該定位資訊是否含有精確度資訊
#4)Criteria(過濾條件)
官方API文檔:
Criteria取得LocationProvider時,可以設定篩選條件,就是透過這個類別來設定相關條件的~
常用方法如下:
- setAccuracy(int accuracy):設定對的精確度需求
- setAltitudeRequired(boolean altitudeRequired):設定是否要求LocationProvider能提供高度的資訊
- setBearingRequired(boolean bearingRequired):設定是否要LocationProvider求能提供方向資訊
- setCostAllowed(boolean costAllowed):設定是否要求LocationProvider能提供方向資訊
- setPowerRequirement(int level):設定要求LocationProvider的耗電量
- setSpeedRequired(boolean speedRequired):設定是否要求LocationProvider能提供速度資訊
2.取得LocationProvider的範例
#運行效果圖:
#由圖可以看到,目前可用的LocationProvider有三個,分別是:
#passive:被動提供,由其他程式提供
gps
:透過GPS取得定位資訊network
:透過網路取得定位資訊
實現程式碼:
佈局檔:
activity_main.xml:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获得系统所有的LocationProvider" />
<Button
android:id="@+id/btn_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="根据条件获取LocationProvider" />
<Button
android:id="@+id/btn_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获取指定的LocationProvider" />
<TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#81BB4D"
android:padding="5dp"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" /></LinearLayout>
MainActivity.java:public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button btn_one; private Button btn_two; private Button btn_three; private TextView tv_result; private LocationManager lm; private List pNames = new ArrayList(); // 存放LocationProvider名称的集合 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); bindViews(); } private void bindViews() { btn_one = (Button) findViewById(R.id.btn_one); btn_two = (Button) findViewById(R.id.btn_two); btn_three = (Button) findViewById(R.id.btn_three); tv_result = (TextView) findViewById(R.id.tv_result); btn_one.setOnClickListener(this); btn_two.setOnClickListener(this); btn_three.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_one: pNames.clear(); pNames = lm.getAllProviders(); tv_result.setText(getProvider()); break; case R.id.btn_two: pNames.clear(); Criteria criteria = new Criteria(); criteria.setCostAllowed(false); //免费 criteria.setAltitudeRequired(true); //能够提供高度信息 criteria.setBearingRequired(true); //能够提供方向信息 pNames = lm.getProviders(criteria, true); tv_result.setText(getProvider()); break; case R.id.btn_three: pNames.clear(); pNames.add(lm.getProvider(LocationManager.GPS_PROVIDER).getName()); //指定名称 tv_result.setText(getProvider()); break; } } //遍历数组返回字符串的方法 private String getProvider(){ StringBuilder sb = new StringBuilder(); for (String s : pNames) { sb.append(s + "\n"); } return sb.toString(); } }3.判斷GPS是否開啟以及開啟GPS的兩種方式
在我們使用GPS定位前的第一件事應該是去判斷GPS是否已經打開或可用,沒打開的話我們需要去 打開GPS才能完成定位!這裡不考慮AGPS的情況~
1)判斷GPS是否可用
private boolean isGpsAble(LocationManager lm){ return lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)?true:false; }2)偵測到GPS未打開,開啟GPS
方法一
:強制開啟GPS,Android 5.0後無用....
//强制帮用户打开GPS 5.0以前可用 private void openGPS(Context context){ Intent gpsIntent = new Intent(); gpsIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); gpsIntent.addCategory("android.intent.category.ALTERNATIVE"); gpsIntent.setData(Uri.parse("custom:3")); try { PendingIntent.getBroadcast(LocationActivity.this, 0, gpsIntent, 0).send(); } catch (PendingIntent.CanceledException e) { e.printStackTrace(); } }方法二
:開啟GPS位置資訊設定頁面,讓使用者自行開啟
//打开位置信息设置页面让用户自己设置 private void openGPS2(){ Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(intent,0); }

這個非常簡單,呼叫requestLocationUpdates方法設定一個LocationListener定時偵測位置而已!
佈局:activity_location.xml
:###<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/tv_show" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="5dp" android:textSize="20sp" android:textStyle="bold" /></LinearLayout>###LocationActivity.java:###
/** * Created by Jay on 2015/11/20 0020. */ public class LocationActivity extends AppCompatActivity { private LocationManager lm; private TextView tv_show; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_location); tv_show = (TextView) findViewById(R.id.tv_show); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!isGpsAble(lm)) { Toast.makeText(LocationActivity.this, "请打开GPS~", Toast.LENGTH_SHORT).show(); openGPS2(); } //从GPS获取最近的定位信息 Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); updateShow(lc); //设置间隔两秒获得一次GPS定位信息 lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8, new LocationListener() { @Override public void onLocationChanged(Location location) { // 当GPS定位信息发生改变时,更新定位 updateShow(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { // 当GPS LocationProvider可用时,更新定位 updateShow(lm.getLastKnownLocation(provider)); } @Override public void onProviderDisabled(String provider) { updateShow(null); } }); } //定义一个更新显示的方法 private void updateShow(Location location) { if (location != null) { StringBuilder sb = new StringBuilder(); sb.append("当前的位置信息:\n"); sb.append("精度:" + location.getLongitude() + "\n"); sb.append("纬度:" + location.getLatitude() + "\n"); sb.append("高度:" + location.getAltitude() + "\n"); sb.append("速度:" + location.getSpeed() + "\n"); sb.append("方向:" + location.getBearing() + "\n"); sb.append("定位精度:" + location.getAccuracy() + "\n"); tv_show.setText(sb.toString()); } else tv_show.setText(""); } private boolean isGpsAble(LocationManager lm) { return lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER) ? true : false; } //打开设置页面让用户自己设置 private void openGPS2() { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(intent, 0); } }###好的,非常簡單,因為gps需要在戶外才能用,所以趁著這個機會小跑出去便利商店買了杯奶茶, 順道截下圖~##############################requestLocationUpdates### (String provider, long minTime, float minDistance, LocationListener listener)###
當時間超過minTime(單位:毫秒),或位置移動超過minDistance(單位:公尺),就會呼叫listener中的方法更新GPS訊息,建議這個minTime不小於60000,即1分鐘,這樣會更有效率而且省電,加入你需要盡量 即時更新GPS,可以將minTime和minDistance設定為0
對了,別忘了,你還需要一枚權限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
#5.臨近警告(地理圍欄)
嗯,就是固定一個點,當手機與該點的距離少於指定範圍時,可以觸發對應的處理! 有點像地理圍欄...我們可以呼叫LocationManager的addProximityAlert方法來新增臨近警告! 完整方法如下:
addProximityAlert(double latitude,double longitude,float radius,long expiration,PendingIntent intent)
屬性說明:
- latitude:指定固定點的經度
- longitude:指定固定點的緯度
- radius:指定半徑長度
- expiration:指定經過多少毫秒後該臨近警告就會過期失效,-1表示永不過期
- intent:此參數指定臨近該固定點時觸發該intent對應的元件
範例程式碼如下:
ProximityActivity.java:
/** * Created by Jay on 2015/11/21 0021. */ public class ProximityActivity extends AppCompatActivity { private LocationManager lm; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_proximity); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //定义固定点的经纬度 double longitude = 113.56843; double latitude = 22.374937; float radius = 10; //定义半径,米 Intent intent = new Intent(this, ProximityReceiver.class); PendingIntent pi = PendingIntent.getBroadcast(this, -1, intent, 0); lm.addProximityAlert(latitude, longitude, radius, -1, pi); } }
還需要註冊一個廣播接收者:ProximityReceiver.java:
/** * Created by Jay on 2015/11/21 0021. */ public class ProximityReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { boolean isEnter = intent.getBooleanExtra( LocationManager.KEY_PROXIMITY_ENTERING, false); if(isEnter) Toast.makeText(context, "你已到达南软B1栋附近", Toast.LENGTH_LONG).show(); else Toast.makeText(context, "你已离开南软B1栋附近", Toast.LENGTH_LONG).show(); } }
別忘了註冊:
<receiver android:name=".ProximityReceiver"/>
運行效果圖:
PS:好吧,設定了10m,結果我從B1走到D1那邊,不只10m了吧...還剛好下雨
6.本節範例程式碼下載
本節小結:
# #好的,本節為大家介紹了Android中GPS定位的一些基本用法,非常簡單,內容部分參考的 李剛老師的《Android瘋狂講義》,只是對例子進行了一些修改以及進行了可用性的測試! 本節就到這裡,謝謝~