[关闭]
@coder-pig 2015-11-21T06:25:50.000000Z 字数 10588 阅读 2272

Android基础入门教程——10.13 Android GPS初涉

Android基础入门教程


本节引言:

 说到GPS这个名词,相信大家都不陌生,GPS全球定位技术嘛,嗯,Android中定位的方式
一般有这四种:GPS定位,WIFI定准,基站定位,AGPS定位(基站+GPS);
本系列教程只讲解GPS定位的基本使用!GPS是通过与卫星交互来获取设备当前的经纬度,准确
度较高,但也有一些缺点,最大的缺点就是:室内几乎无法使用...需要收到4颗卫星或以上
信号才能保证GPS的准确定位!但是假如你是在室外,无网络的情况,GPS还是可以用的!
本节我们就来探讨下Android中的GPS的基本用法~


1.定位相关的一些API


1)LocationManager

官方API文档:LocationManager
这玩意是系统服务来的,不能直接new,需要:

  1. LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

另外用GPS定位别忘了加权限:

  1. <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文档:Location
位置信息的抽象类,我们可以调用下述方法获取相关的定位信息!
常用方法如下:

  • 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

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:orientation="vertical">
  5. <Button
  6. android:id="@+id/btn_one"
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:text="获得系统所有的LocationProvider" />
  10. <Button
  11. android:id="@+id/btn_two"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="根据条件获取LocationProvider" />
  15. <Button
  16. android:id="@+id/btn_three"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:text="获取指定的LocationProvider" />
  20. <TextView
  21. android:id="@+id/tv_result"
  22. android:layout_width="match_parent"
  23. android:layout_height="match_parent"
  24. android:layout_margin="10dp"
  25. android:background="#81BB4D"
  26. android:padding="5dp"
  27. android:textColor="#FFFFFF"
  28. android:textSize="20sp"
  29. android:textStyle="bold" />
  30. </LinearLayout>

MainActivity.java:

  1. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  2. private Button btn_one;
  3. private Button btn_two;
  4. private Button btn_three;
  5. private TextView tv_result;
  6. private LocationManager lm;
  7. private List<String> pNames = new ArrayList<String>(); // 存放LocationProvider名称的集合
  8. @Override
  9. protected void onCreate(Bundle savedInstanceState) {
  10. super.onCreate(savedInstanceState);
  11. setContentView(R.layout.activity_main);
  12. lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  13. bindViews();
  14. }
  15. private void bindViews() {
  16. btn_one = (Button) findViewById(R.id.btn_one);
  17. btn_two = (Button) findViewById(R.id.btn_two);
  18. btn_three = (Button) findViewById(R.id.btn_three);
  19. tv_result = (TextView) findViewById(R.id.tv_result);
  20. btn_one.setOnClickListener(this);
  21. btn_two.setOnClickListener(this);
  22. btn_three.setOnClickListener(this);
  23. }
  24. @Override
  25. public void onClick(View v) {
  26. switch (v.getId()) {
  27. case R.id.btn_one:
  28. pNames.clear();
  29. pNames = lm.getAllProviders();
  30. tv_result.setText(getProvider());
  31. break;
  32. case R.id.btn_two:
  33. pNames.clear();
  34. Criteria criteria = new Criteria();
  35. criteria.setCostAllowed(false); //免费
  36. criteria.setAltitudeRequired(true); //能够提供高度信息
  37. criteria.setBearingRequired(true); //能够提供方向信息
  38. pNames = lm.getProviders(criteria, true);
  39. tv_result.setText(getProvider());
  40. break;
  41. case R.id.btn_three:
  42. pNames.clear();
  43. pNames.add(lm.getProvider(LocationManager.GPS_PROVIDER).getName()); //指定名称
  44. tv_result.setText(getProvider());
  45. break;
  46. }
  47. }
  48. //遍历数组返回字符串的方法
  49. private String getProvider(){
  50. StringBuilder sb = new StringBuilder();
  51. for (String s : pNames) {
  52. sb.append(s + "\n");
  53. }
  54. return sb.toString();
  55. }
  56. }

3.判断GPS是否打开以及打开GPS的两种方式

在我们使用GPS定位前的第一件事应该是去判断GPS是否已经打开或可用,没打开的话我们需要去
打开GPS才能完成定位!这里不考虑AGPS的情况~


1)判断GPS是否可用

  1. private boolean isGpsAble(LocationManager lm){
  2. return lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)?true:false;
  3. }

2)检测到GPS未打开,打开GPS

方法一:强制打开GPS,Android 5.0后无用....

  1. //强制帮用户打开GPS 5.0以前可用
  2. private void openGPS(Context context){
  3. Intent gpsIntent = new Intent();
  4. gpsIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
  5. gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
  6. gpsIntent.setData(Uri.parse("custom:3"));
  7. try {
  8. PendingIntent.getBroadcast(LocationActivity.this, 0, gpsIntent, 0).send();
  9. } catch (PendingIntent.CanceledException e) {
  10. e.printStackTrace();
  11. }
  12. }

方法二:打开GPS位置信息设置页面,让用户自行打开

  1. //打开位置信息设置页面让用户自己设置
  2. private void openGPS2(){
  3. Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  4. startActivityForResult(intent,0);
  5. }

4.动态获取位置信息

这个非常简单,调用requestLocationUpdates方法设置一个LocationListener定时检测位置而已!
示例代码如下:

布局:activity_location.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <TextView
  7. android:id="@+id/tv_show"
  8. android:layout_width="match_parent"
  9. android:layout_height="match_parent"
  10. android:padding="5dp"
  11. android:textSize="20sp"
  12. android:textStyle="bold" />
  13. </LinearLayout>

LocationActivity.java:

  1. /**
  2. * Created by Jay on 2015/11/20 0020.
  3. */
  4. public class LocationActivity extends AppCompatActivity {
  5. private LocationManager lm;
  6. private TextView tv_show;
  7. @Override
  8. public void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_location);
  11. tv_show = (TextView) findViewById(R.id.tv_show);
  12. lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  13. if (!isGpsAble(lm)) {
  14. Toast.makeText(LocationActivity.this, "请打开GPS~", Toast.LENGTH_SHORT).show();
  15. openGPS2();
  16. }
  17. //从GPS获取最近的定位信息
  18. Location lc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
  19. updateShow(lc);
  20. //设置间隔两秒获得一次GPS定位信息
  21. lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 8, new LocationListener() {
  22. @Override
  23. public void onLocationChanged(Location location) {
  24. // 当GPS定位信息发生改变时,更新定位
  25. updateShow(location);
  26. }
  27. @Override
  28. public void onStatusChanged(String provider, int status, Bundle extras) {
  29. }
  30. @Override
  31. public void onProviderEnabled(String provider) {
  32. // 当GPS LocationProvider可用时,更新定位
  33. updateShow(lm.getLastKnownLocation(provider));
  34. }
  35. @Override
  36. public void onProviderDisabled(String provider) {
  37. updateShow(null);
  38. }
  39. });
  40. }
  41. //定义一个更新显示的方法
  42. private void updateShow(Location location) {
  43. if (location != null) {
  44. StringBuilder sb = new StringBuilder();
  45. sb.append("当前的位置信息:\n");
  46. sb.append("精度:" + location.getLongitude() + "\n");
  47. sb.append("纬度:" + location.getLatitude() + "\n");
  48. sb.append("高度:" + location.getAltitude() + "\n");
  49. sb.append("速度:" + location.getSpeed() + "\n");
  50. sb.append("方向:" + location.getBearing() + "\n");
  51. sb.append("定位精度:" + location.getAccuracy() + "\n");
  52. tv_show.setText(sb.toString());
  53. } else tv_show.setText("");
  54. }
  55. private boolean isGpsAble(LocationManager lm) {
  56. return lm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER) ? true : false;
  57. }
  58. //打开设置页面让用户自己设置
  59. private void openGPS2() {
  60. Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
  61. startActivityForResult(intent, 0);
  62. }
  63. }

好的,非常简单,因为gps需要在室外才能用,于是趁着这个机会小跑出去便利店买了杯奶茶,
顺道截下图~

requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)
当时间超过minTime(单位:毫秒),或者位置移动超过minDistance(单位:米),就会调用listener中的方法更新GPS信息,建议这个minTime不小于60000,即1分钟,这样会更加高效而且省电,加入你需要尽可能
实时地更新GPS,可以将minTime和minDistance设置为0

对了,别忘了,你还需要一枚权限:

  1. <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

  1. /**
  2. * Created by Jay on 2015/11/21 0021.
  3. */
  4. public class ProximityActivity extends AppCompatActivity {
  5. private LocationManager lm;
  6. @Override
  7. public void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.activity_proximity);
  10. lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  11. //定义固定点的经纬度
  12. double longitude = 113.56843;
  13. double latitude = 22.374937;
  14. float radius = 10; //定义半径,米
  15. Intent intent = new Intent(this, ProximityReceiver.class);
  16. PendingIntent pi = PendingIntent.getBroadcast(this, -1, intent, 0);
  17. lm.addProximityAlert(latitude, longitude, radius, -1, pi);
  18. }
  19. }

还需要注册一个广播接收者:ProximityReceiver.java

  1. /**
  2. * Created by Jay on 2015/11/21 0021.
  3. */
  4. public class ProximityReceiver extends BroadcastReceiver{
  5. @Override
  6. public void onReceive(Context context, Intent intent) {
  7. boolean isEnter = intent.getBooleanExtra( LocationManager.KEY_PROXIMITY_ENTERING, false);
  8. if(isEnter) Toast.makeText(context, "你已到达南软B1栋附近", Toast.LENGTH_LONG).show();
  9. else Toast.makeText(context, "你已离开南软B1栋附近", Toast.LENGTH_LONG).show();
  10. }
  11. }

别忘了注册:

  1. <receiver android:name=".ProximityReceiver"/>

运行效果图

PS:好吧,设置了10m,结果我从B1走到D1那边,不止10m了吧...还刚好下雨


6.本节示例代码下载

GPSDemo.zip


本节小结:

好的,本节给大家介绍了Android中GPS定位的一些基本用法,非常简单,内容部分参考的
李刚老师的《Android疯狂讲义》,只是对例子进行了一些修改以及进行了可用性的测试!
本节就到这里,谢谢~

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注