Android GPS初涉
本節(jié)引言:
說(shuō)到GPS這個(gè)名詞,相信大家都不陌生,GPS全球定位技術(shù)嘛,嗯,Android中定位的方式 一般有這四種:GPS定位,WIFI定準(zhǔn),基站定位,AGPS定位(基站+GPS);
本系列教程只講解GPS定位的基本使用!GPS是通過(guò)與衛(wèi)星交互來(lái)獲取設(shè)備當(dāng)前的經(jīng)緯度,準(zhǔn)確 度較高,但也有一些缺點(diǎn),最大的缺點(diǎn)就是:室內(nèi)幾乎無(wú)法使用...需要收到4顆衛(wèi)星或以上 信號(hào)才能保證GPS的準(zhǔn)確定位!但是假如你是在室外,無(wú)網(wǎng)絡(luò)的情況,GPS還是可以用的!
本節(jié)我們就來(lái)探討下Android中的GPS的基本用法~
1.定位相關(guān)的一些API
1)LocationManager
官方API文檔:LocationManager
這玩意是系統(tǒng)服務(wù)來(lái)的,不能直接new,需要:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
另外用GPS定位別忘了加權(quán)限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
好的,獲得了LocationManager對(duì)象后,我們可以調(diào)用下面這些常用的方法:
- addGpsStatusListener(GpsStatus.Listener listener):添加一個(gè)GPS狀態(tài)監(jiān)聽(tīng)器
- addProximityAlert(double latitude, double longitude, float radius, long expiration, PendingIntent intent): 添加一個(gè)臨界警告
- getAllProviders():獲取所有的LocationProvider列表
- getBestProvider(Criteria criteria, boolean enabledOnly):根據(jù)指定條件返回最優(yōu)LocationProvider
- getGpsStatus(GpsStatus status):獲取GPS狀態(tài)
- getLastKnownLocation(String provider):根據(jù)LocationProvider獲得最近一次已知的Location
- getProvider(String name):根據(jù)名稱來(lái)獲得LocationProvider
- getProviders(boolean enabledOnly):獲取所有可用的LocationProvider
- getProviders(Criteria criteria, boolean enabledOnly):根據(jù)指定條件獲取滿足條件的所有LocationProvider
- isProviderEnabled(String provider):判斷指定名稱的LocationProvider是否可用
- removeGpsStatusListener(GpsStatus.Listener listener):刪除GPS狀態(tài)監(jiān)聽(tīng)器
- removeProximityAlert(PendingIntent intent):刪除一個(gè)臨近警告
- requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntent intent): 通過(guò)制定的LocationProvider周期性地獲取定位信息,并通過(guò)Intent啟動(dòng)相應(yīng)的組件
- requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener): 通過(guò)制定的LocationProvider周期性地獲取定位信息,并觸發(fā)listener所對(duì)應(yīng)的觸發(fā)器
2)LocationProvider(定位提供者)
官方API文檔:LocationProvider
這比是GPS定位組件的抽象表示,調(diào)用下述方法可以獲取該定位組件的相關(guān)信息!
常用的方法如下:
- getAccuracy():返回LocationProvider精度
- getName():返回LocationProvider名稱
- getPowerRequirement():獲取LocationProvider的電源需求
- hasMonetaryCost():返回該LocationProvider是收費(fèi)還是免費(fèi)的
- meetsCriteria(Criteria criteria):判斷LocationProvider是否滿足Criteria條件
- requiresCell():判斷LocationProvider是否需要訪問(wèn)網(wǎng)絡(luò)基站
- requiresNetwork():判斷LocationProvider是否需要訪問(wèn)網(wǎng)絡(luò)數(shù)據(jù)
- requiresSatellite():判斷LocationProvider是否需要訪問(wèn)基于衛(wèi)星的定位系統(tǒng)
- supportsAltitude():判斷LocationProvider是否支持高度信息
- supportsBearing():判斷LocationProvider是否支持方向信息
- supportsSpeed():判斷是LocationProvider否支持速度信息
3)Location(位置信息)
官方API文檔:Location
位置信息的抽象類,我們可以調(diào)用下述方法獲取相關(guān)的定位信息!
常用方法如下:
- float getAccuracy():獲得定位信息的精度
- double getAltitude():獲得定位信息的高度
- float getBearing():獲得定位信息的方向
- double getLatitude():獲得定位信息的緯度
- double getLongitude():獲得定位信息的精度
- String getProvider():獲得提供該定位信息的LocationProvider
- float getSpeed():獲得定位信息的速度
- boolean hasAccuracy():判斷該定位信息是否含有精度信息
4)Criteria(過(guò)濾條件)
官方API文檔:Criteria
獲取LocationProvider時(shí),可以設(shè)置過(guò)濾條件,就是通過(guò)這個(gè)類來(lái)設(shè)置相關(guān)條件的~
常用方法如下:
- setAccuracy(int accuracy):設(shè)置對(duì)的精度要求
- setAltitudeRequired(boolean altitudeRequired):設(shè)置是否要求LocationProvider能提供高度的信息
- setBearingRequired(boolean bearingRequired):設(shè)置是否要LocationProvider求能提供方向信息
- setCostAllowed(boolean costAllowed):設(shè)置是否要求LocationProvider能提供方向信息
- setPowerRequirement(int level):設(shè)置要求LocationProvider的耗電量
- setSpeedRequired(boolean speedRequired):設(shè)置是否要求LocationProvider能提供速度信息
2.獲取LocationProvider的例子
運(yùn)行效果圖:
由圖可以看到,當(dāng)前可用的LocationProvider有三個(gè),分別是:
- passive:被動(dòng)提供,由其他程序提供
- gps:通過(guò)GPS獲取定位信息
- network:通過(guò)網(wǎng)絡(luò)獲取定位信息
實(shí)現(xiàn)代碼:
布局文件: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="獲得系統(tǒng)所有的LocationProvider" /> <Button android:id="@+id/btn_two" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="根據(jù)條件獲取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); //免費(fèi) 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; } } //遍歷數(shù)組返回字符串的方法 private String getProvider(){ StringBuilder sb = new StringBuilder(); for (String s : pNames) { sb.append(s + "\n"); } return sb.toString(); } }
3.判斷GPS是否打開(kāi)以及打開(kāi)GPS的兩種方式
在我們使用GPS定位前的第一件事應(yīng)該是去判斷GPS是否已經(jīng)打開(kāi)或可用,沒(méi)打開(kāi)的話我們需要去 打開(kāi)GPS才能完成定位!這里不考慮AGPS的情況~
1)判斷GPS是否可用
private boolean isGpsAble(LocationManager lm){ return lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)?true:false; }
2)檢測(cè)到GPS未打開(kāi),打開(kāi)GPS
方法一:強(qiáng)制打開(kāi)GPS,Android 5.0后無(wú)用....
//強(qiáng)制幫用戶打開(kāi)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(); } }
方法二:打開(kāi)GPS位置信息設(shè)置頁(yè)面,讓用戶自行打開(kāi)
//打開(kāi)位置信息設(shè)置頁(yè)面讓用戶自己設(shè)置 private void openGPS2(){ Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(intent,0); }
4.動(dòng)態(tài)獲取位置信息
這個(gè)非常簡(jiǎn)單,調(diào)用requestLocationUpdates方法設(shè)置一個(gè)LocationListener定時(shí)檢測(cè)位置而已!
示例代碼如下:
布局: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, "請(qǐng)打開(kāi)GPS~", Toast.LENGTH_SHORT).show(); openGPS2(); } //從GPS獲取最近的定位信息 Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); updateShow(lc); //設(shè)置間隔兩秒獲得一次GPS定位信息 lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8, new LocationListener() { @Override public void onLocationChanged(Location location) { // 當(dāng)GPS定位信息發(fā)生改變時(shí),更新定位 updateShow(location); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { // 當(dāng)GPS LocationProvider可用時(shí),更新定位 updateShow(lm.getLastKnownLocation(provider)); } @Override public void onProviderDisabled(String provider) { updateShow(null); } }); } //定義一個(gè)更新顯示的方法 private void updateShow(Location location) { if (location != null) { StringBuilder sb = new StringBuilder(); sb.append("當(dāng)前的位置信息:\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; } //打開(kāi)設(shè)置頁(yè)面讓用戶自己設(shè)置 private void openGPS2() { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivityForResult(intent, 0); } }
好的,非常簡(jiǎn)單,因?yàn)間ps需要在室外才能用,于是趁著這個(gè)機(jī)會(huì)小跑出去便利店買了杯奶茶, 順道截下圖~
requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)
當(dāng)時(shí)間超過(guò)minTime(單位:毫秒),或者位置移動(dòng)超過(guò)minDistance(單位:米),就會(huì)調(diào)用listener中的方法更新GPS信息,建議這個(gè)minTime不小于60000,即1分鐘,這樣會(huì)更加高效而且省電,加入你需要盡可能 實(shí)時(shí)地更新GPS,可以將minTime和minDistance設(shè)置為0
對(duì)了,別忘了,你還需要一枚權(quán)限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
5.臨近警告(地理圍欄)
嗯,就是固定一個(gè)點(diǎn),當(dāng)手機(jī)與該點(diǎn)的距離少于指定范圍時(shí),可以觸發(fā)對(duì)應(yīng)的處理! 有點(diǎn)像地理圍欄...我們可以調(diào)用LocationManager的addProximityAlert方法添加臨近警告! 完整方法如下:
addProximityAlert(double latitude,double longitude,float radius,long expiration,PendingIntent intent)
屬性說(shuō)明:
- latitude:指定固定點(diǎn)的經(jīng)度
- longitude:指定固定點(diǎn)的緯度
- radius:指定半徑長(zhǎng)度
- expiration:指定經(jīng)過(guò)多少毫秒后該臨近警告就會(huì)過(guò)期失效,-1表示永不過(guò)期
- intent:該參數(shù)指定臨近該固定點(diǎn)時(shí)觸發(fā)該intent對(duì)應(yīng)的組件
示例代碼如下:
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); //定義固定點(diǎn)的經(jīng)緯度 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); } }
還需要注冊(cè)一個(gè)廣播接收者: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, "你已到達(dá)南軟B1棟附近", Toast.LENGTH_LONG).show(); else Toast.makeText(context, "你已離開(kāi)南軟B1棟附近", Toast.LENGTH_LONG).show(); } }
別忘了注冊(cè):
<receiver android:name=".ProximityReceiver"/>
運(yùn)行效果圖:
PS:好吧,設(shè)置了10m,結(jié)果我從B1走到D1那邊,不止10m了吧...還剛好下雨
6.本節(jié)示例代碼下載
本節(jié)小結(jié):
好的,本節(jié)給大家介紹了Android中GPS定位的一些基本用法,非常簡(jiǎn)單,內(nèi)容部分參考的 李剛老師的《Android瘋狂講義》,只是對(duì)例子進(jìn)行了一些修改以及進(jìn)行了可用性的測(cè)試! 本節(jié)就到這里,謝謝~