加载中...

10.13 Android GPS初涉


本节引言:

说到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.  
  6.     <Button
  7.         android:id="@+id/btn_one"
  8.         android:layout_width="wrap_content"
  9.         android:layout_height="wrap_content"
  10.         android:text="获得系统所有的LocationProvider" />
  11.  
  12.     <Button
  13.         android:id="@+id/btn_two"
  14.         android:layout_width="wrap_content"
  15.         android:layout_height="wrap_content"
  16.         android:text="根据条件获取LocationProvider" />
  17.  
  18.     <Button
  19.         android:id="@+id/btn_three"
  20.         android:layout_width="wrap_content"
  21.         android:layout_height="wrap_content"
  22.         android:text="获取指定的LocationProvider" />
  23.  
  24.     <TextView
  25.         android:id="@+id/tv_result"
  26.         android:layout_width="match_parent"
  27.         android:layout_height="match_parent"
  28.         android:layout_margin="10dp"
  29.         android:background="#81BB4D"
  30.         android:padding="5dp"
  31.         android:textColor="#FFFFFF"
  32.         android:textSize="20sp"
  33.         android:textStyle="bold" />
  34.  
  35. </LinearLayout>

MainActivity.java:

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

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.  
  7.     <TextView
  8.         android:id="@+id/tv_show"
  9.         android:layout_width="match_parent"
  10.         android:layout_height="match_parent"
  11.         android:padding="5dp"
  12.         android:textSize="20sp"
  13.         android:textStyle="bold" />
  14.  
  15. </LinearLayout>

LocationActivity.java:

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

好的,非常简单,因为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了吧...还刚好下雨

 

本节小结:

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

下载地址


还没有评论.