目录

定位服务开发指南

要使用华为定位服务API,需要确保您的设备已经下载并安装了HMS Core服务组件,并将相关的SDK集成到您的项目中。有关详细信息,请参阅开发准备。

1. 定位服务开发步骤

1.1 指定应用权限

1、Android提供了两种位置权限: ACCESS_COARSE_LOCATION(粗略的位置权限) 和ACCESS_FINE_LOCATION(精确的位置权限)。需要在Manifest文件中申请权限:

  1. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  2. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

2、在Android Q版本中,如果您需要应用程序在后台执行时也具备持续定位能力,需要在Manifest文件中申请ACCESS_BACKGROUND_LOCATION权限:

  1. <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

3、在Manifest中添加后,还要在代码中动态申请一下权限(Android 6.0危险权限要求):      

  1. if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
  2.    Log.i(TAG, "sdk < 28 Q");
  3.    if (ActivityCompat.checkSelfPermission(this,
  4.        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
  5.        || ActivityCompat.checkSelfPermission(this,
  6.            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
  7.        String[] strings =
  8.            {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
  9.        ActivityCompat.requestPermissions(this, strings, 1);
  10.    }
  11. } else {
  12.    if (ActivityCompat.checkSelfPermission(this,
  13.        Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
  14.        || ActivityCompat.checkSelfPermission(this,
  15.            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
  16.        || ActivityCompat.checkSelfPermission(this,
  17.            "android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED) {
  18.        String[] strings = {android.Manifest.permission.ACCESS_FINE_LOCATION,
  19.            android.Manifest.permission.ACCESS_COARSE_LOCATION,
  20.            "android.permission.ACCESS_BACKGROUND_LOCATION"};
  21.        ActivityCompat.requestPermissions(this, strings, 2);
  22.    }
  23. }

1.2 创建定位服务客户端

在Activity的OnCreate()方法中创建一个FusedLocationProviderClient实例,通过该实例调用定位相关接口。

  1. private FusedLocationProviderClient fusedLocationProviderClient;
  2. private LocationRequest mLocationRequest;        
  3. protected void onCreate(Bundle savedInstanceState) {  
  4.    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
  5. }

1.3 检查设备定位设置

设备的相关定位设置会影响华为定位服务的定位结果,例如位置开关选项处于关闭状态时,将无法获取到位置信息。因此,建议您在持续获取位置信息之前,先检查设备设置是否满足定位条件。华为定位服务提供了检查设备定位相关设置的能力,通过LocationServices的getSettingsClient(Activity activity)获取SettingsClient实例,然后调用checkLocationSettings( LocationSettingsRequest locationSettingsRequest)接口获取定位设置结果,当设置不满足定位条件时,将为您提供解决方案以提示用户打开对应的权限(HMS Core 定位权限必须打开,Android Q版本必须选择“始终允许”)。

1、获取SettingsClient的服务接口

  1. SettingsClient settingsClient = LocationServices.getSettingsClient(this);

2、调用checkLocationSettings()检查设备设置

  1. LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
  2. mLocationRequest = new LocationRequest();
  3. builder.addLocationRequest(mLocationRequest);
  4. LocationSettingsRequest locationSettingsRequest = builder.build();
  5. //检查设备定位设置
  6. settingsClient.checkLocationSettings(locationSettingsRequest)
  7.        .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
  8.            @Override
  9.            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
  10.                //设置满足定位条件,再发起位置请求
  11.                fusedLocationProviderClient
  12.                        .requestLocationUpdates(mLocationRequest, mLocationCallback,Looper.getMainLooper())
  13.                        .addOnSuccessListener(new OnSuccessListener<Void>() {
  14.                            @Override
  15.                            public void onSuccess(Void aVoid) {
  16.                                //接口调用成功的处理
  17.                            }
  18.                        });
  19.            }
  20.        })
  21.        .addOnFailureListener(new OnFailureListener() {
  22.            @Override
  23.            public void onFailure(Exception e) {
  24.                //设置不满足定位条件
  25.                int statusCode = ((ApiException) e).getStatusCode();
  26.                switch (statusCode) {
  27.                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
  28.                        try {
  29.                            ResolvableApiException rae = (ResolvableApiException) e;
  30.                            //调用startResolutionForResult可以弹窗提示用户打开相应权限
  31.                            rae.startResolutionForResult(MainActivity.this, 0);
  32.                        } catch (IntentSender.SendIntentException sie) {
  33.                            //…
  34.                        }
  35.                        break;
  36.                }
  37.            }
  38.        });

1.4 持续获取位置信息

如果您希望应用可以持续获取设备位置,可以使用华为定位服务提供的requestLocationUpdates()接口。该接口根据入参形式的不同,将以两种不同的形式将位置信息返回。一种是通过调用您已经定义的LocationCallback.onLocationResult()回调方法返回一个包含位置信息的LocationResult对象,另一种是将位置信息置于Pendingintent扩展信息中返回。

当您的应用程序不再需要接收位置更新时,应当停止位置更新,以便于降低功耗。要停止位置更新,可以调用removeLocationUpdates(),传入与requestLocationUpdates()接口相对应的LocationCallback或Pendingintent对象。这里以回调方式作为样例,代码如下。详细的参数说明见location接口说明。

1、设置持续定位请求参数

  1. LocationRequest mLocationRequest = new LocationRequest();        
  2. //设置位置更新的间隔(毫秒为单位)        
  3. mLocationRequest.setInterval(10000);        
  4. //设置权重        
  5. mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

2、定义位置更新回调 

  1. LocationCallback mLocationCallback;        
  2. mLocationCallback = new LocationCallback() {        
  3.               @Override        
  4.               public void onLocationResult(LocationResult locationResult) {        
  5.                   if (locationResult != null) {        
  6.                       //处理位置回调结果        
  7.                   }        
  8.               }        
  9.           };

3、调用requestLocationUpdates()进行持续定位

  1. fusedLocationProviderClient        
  2.                   .requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())        
  3.                   .addOnSuccessListener(new OnSuccessListener<Void>() {        
  4.                       @Override        
  5.                       public void onSuccess(Void aVoid) {        
  6.                           //接口调用成功的处理        
  7.                       }        
  8.                   })
  9.                   .addOnFailureListener(new OnFailureListener() {        
  10.                       @Override        
  11.                       public void onFailure(Exception e) {        
  12.                           //接口调用失败的处理        
  13.                       }        
  14.                   });
注意:
如果接口调用成功,获取位置信息失败,请参考FAQ[3]。

4、调用removeLocationUpdates()停止位置更新

  1. //注意:停止位置更新时,mLocationCallback必须与requestLocationUpdates方法中的LocationCallback参数为同一对象。
  2. fusedLocationProviderClient.removeLocationUpdates(mLocationCallback)        
  3.               .addOnSuccessListener(new OnSuccessListener<Void>() {        
  4.                   @Override        
  5.                   public void onSuccess(Void aVoid) {      
  6.                       //停止位置更新成功        
  7.                   }        
  8.               })
  9.               .addOnFailureListener(new OnFailureListener() {        
  10.                   @Override        
  11.                   public void onFailure(Exception e) {      
  12.                       //停止位置更新失败        
  13.                   }        
  14.               });

1.5 获取最后的已知位置

使用华为定位服务API,您的应用程序可以获取设备最后的已知位置,大多情况下,该位置即为设备的当前位置。调用getLastLocation()方法获取最后的已知位置的代码样例如下:

  1. Task<Location> task = fusedLocationProviderClient.getLastLocation()        
  2.               .addOnSuccessListener(new OnSuccessListener<Location>() {        
  3.                   @Override      
  4.                   public void onSuccess(Location location) {        
  5.                       if (location == null) {        
  6.                           return;        
  7.                       }        
  8.                       //Location对象的处理逻辑      
  9.                   }        
  10.               })
  11.               .addOnFailureListener(new OnFailureListener() {        
  12.                   @Override        
  13.                   public void onFailure(Exception e) {        
  14.                       //异常处理逻辑        
  15.                   }        
  16.               });

1.6 使用模拟位置信息功能

具体操作步骤:打开设置 -> 系统和更新 -> 开发人员选项 -> 选择模拟位置信息应用 -> 选择要mock的应用(如果没有发现“开发人员选项”,请执行如下操作:设置 -> 关于手机 -> 版本号,连续点击"版本号"7次,"开发人员选项"会出现在"系统与更新"页面,再重复上述操作),示例代码如下:

1、设置mock模式,调用setMockMode(boolean isMockMode)。

  1. fusedLocationProviderClient.setMockMode(mockFlag)
  2.                        .addOnSuccessListener(new OnSuccessListener<Void>() {
  3.                            @Override
  4.                            public void onSuccess(Void aVoid) {
  5.                                Log.i(TAG, "setMockMode onSuccess");
  6.                            }
  7.                        })
  8.                        .addOnFailureListener(new OnFailureListener() {
  9.                            @Override
  10.                            public void onFailure(Exception e) {
  11.                                Log.i(TAG, "setMockMode onFailure:" + e.getMessage());
  12.                            }
  13.                        });

2、设置模拟位置信息,调用setMockLocation(Location mockLocation)。

  1. fusedLocationProviderClient.setMockLocation(mockLocation)
  2.                        .addOnSuccessListener(new OnSuccessListener<Void>() {
  3.                            @Override
  4.                            public void onSuccess(Void aVoid) {
  5.                                Log.i(TAG, "setMockLocation onSuccess");
  6.                            }
  7.                        })
  8.                        .addOnFailureListener(new OnFailureListener() {
  9.                            @Override
  10.                            public void onFailure(Exception e) {
  11.                                Log.i(TAG, "setMockLocation onFailure:" + e.getMessage());
  12.                            }
  13.                        });

2. 活动识别服务开发步骤

要使用华为活动识别服务API,需要确保您的设备已经下载并安装了HMS Core(APK),并将相关的SDK集成到您的项目中。有关详细信息,请参阅开发准备。以下仅为代码片段,详情请参考完整示例代码

2.1 指定应用权限

1、在Android Q以下版本使用活动识别需要在manifest文件中配置以下权限:

  1. <uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION"/>

2、在Android Q及以上版本中,需要在Manifest文件中申请以下权限:

  1. <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
说明:
以上权限属于危险权限,使用时需要动态申请。        

2.2 创建活动识别服务客户端

在Activity的OnCreate()方法中创建一个ActivityIdentificationService实例,通过该实例调用活动识别相关接口:

  1. //获取PendingIntent及回调结果的方式可自定义,这里以广播为例进行说明
  2. private PendingIntent pendingIntent;
  3. private ActivityIdentificationService activityIdentificationService;
  4. protected void onCreate(Bundle savedInstanceState) {
  5.    activityIdentificationService = ActivityIdentification.getService(this);
  6.    pendingIntent = getPendingIntent();
  7. };

2.3 活动识别更新

使用活动识别服务,首先需要您注册活动识别更新,可以检测用户当前是步行,骑自行车,静止等状态。

1、新建PendingIntent

  1. private PendingIntent getPendingIntent() {
  2.    //LocationBroadcastReceiver类为自定义静态广播类,详细的实现方法可以参照示例代码。
  3.    Intent intent = new Intent(this, LocationBroadcastReceiver.class);
  4.    intent.setAction(LocationBroadcastReceiver.ACTION_PROCESS_LOCATION);
  5.    return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  6. }

2、监听活动识别更新请求

通过调用createActivityIdentificationUpdates(long detectionIntervalMillis, PendingIntent pendingIntent)方法,第一个参数为更新的周期,第二个参数pendingIntent。

  1. activityIdentificationService.createActivityIdentificationUpdates(5000, pendingIntent)
  2.    .addOnSuccessListener(new OnSuccessListener<Void>() {
  3.        @Override
  4.        public void onSuccess(Void aVoid) {
  5.            Log.i(TAG, "createActivityIdentificationUpdates onSuccess");
  6.        }
  7.    })
  8.    .addOnFailureListener(new OnFailureListener() {
  9.        @Override
  10.        public void onFailure(Exception e) {
  11.            Log.e(TAG, "createActivityIdentificationUpdates onFailure:" + e.getMessage());
  12.        }
  13.    });

3、移除活动识别更新

在使用完活动识别后需要进行移除操作,移除活动识别定时监听,参数PendingIntent必须与createActivityIdentificationUpdates (long detectionIntervalMillis, PendingIntent callbackIntent)参数里的PendingIntent是同一个。

  1. activityIdentificationService.deleteActivityIdentificationUpdates(pendingIntent)
  2.    .addOnSuccessListener(new OnSuccessListener<Void>() {
  3.        @Override
  4.        public void onSuccess(Void aVoid) {
  5.            Log.i(TAG, "deleteActivityIdentificationUpdates onSuccess");
  6.        }
  7.    })
  8.    .addOnFailureListener(new OnFailureListener() {
  9.        @Override
  10.        public void onFailure(Exception e) {
  11.            Log.e(TAG, "deleteActivityIdentificationUpdates onFailure:" + e.getMessage());
  12.        }
  13.    });

4、活动识别结果获取

通过Pendingintent获取活动识别结果。

  1. public class LocationBroadcastReceiver extends BroadcastReceiver {
  2.    public static final String ACTION_PROCESS_LOCATION = "com.huawei.hms.location.ACTION_PROCESS_LOCATION";
  3.    @Override
  4.    public void onReceive(Context context, Intent intent) {
  5.        if (intent != null) {
  6.            final String action = intent.getAction();
  7.            if (ACTION_PROCESS_LOCATION.equals(action)) {
  8.                 ActivityIdentificationResponse activityIdentificationResponse = ActivityIdentificationResponse.getDataFromIntent(intent);
  9.                 List<ActivityIdentificationData> list = activityIdentificationResponse .getActivityIdentificationDatas();
  10.            }
  11.        }
  12.    }
  13. }

2.4 活动过渡更新

接口提供检测活动过渡条件(进入,退出)的功能,例如需要检测用户从走路变为骑自行车的状态时,应用通过调用createActivityConversionUpdates(request, pendingIntent)方法获取活动过渡的状态变化。

1、设置监听活动过渡请求参数

  1. int STILL = 103;
  2. ActivityConversionInfo activityConversionInfo1 = new ActivityConversionInfo(STILL, ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION);
  3. ActivityConversionInfo activityConversionInfo2 = new ActivityConversionInfo(STILL, ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION);
  4. List<ActivityConversionInfo> activityConversionInfos = new ArrayList<>();
  5. activityConversionInfos.add(activityConversionInfo1);
  6. activityConversionInfos.add(activityConversionInfo2);
  7. ActivityConversionRequest request = new ActivityConversionRequest();
  8. request.setActivityConversions(activityConversionInfos);

2、监听活动过渡更新

  1. Task<Void> task = activityIdentificationService.createActivityConversionUpdates(request, pendingIntent);
  2. task.addOnSuccessListener(new OnSuccessListener<Void>() {
  3.    @Override
  4.    public void onSuccess(Void aVoid) {
  5.        Log.i(TAG, "createActivityConversionUpdates onSuccess");
  6.    }
  7. }).addOnFailureListener(new OnFailureListener() {
  8.    @Override
  9.    public void onFailure(Exception e) {
  10.        Log.e(TAG, "createActivityConversionUpdates onFailure:" + e.getMessage());
  11.    }
  12. });

3、移除活动过渡更新

不需要监听活动过渡条件时,需要调用deleteActivityConversionUpdates(PendingIntent pendingIntent)进行移除操作。

  1. activityIdentificationService.deleteActivityConversionUpdates(pendingIntent)
  2.    .addOnSuccessListener(new OnSuccessListener<Void>() {
  3.        @Override
  4.        public void onSuccess(Void aVoid) {
  5.            Log.i(TAG, "deleteActivityConversionUpdates onSuccess");
  6.        }
  7.    })
  8.    .addOnFailureListener(new OnFailureListener() {
  9.        @Override
  10.        public void onFailure(Exception e) {
  11.            Log.e(TAG, "deleteActivityConversionUpdates onFailure:" + e.getMessage());
  12.        }
  13.    });

4、返回结果获取

活动过渡的结果

  1. public class LocationBroadcastReceiver extends BroadcastReceiver {
  2.    public static final String ACTION_PROCESS_LOCATION = "com.huawei.hms.location.ACTION_PROCESS_LOCATION";
  3.    @Override
  4.    public void onReceive(Context context, Intent intent) {
  5.        if (intent != null) {
  6.            final String action = intent.getAction();
  7.            if (ACTION_PROCESS_LOCATION.equals(action)) {
  8.                ActivityConversionResponse activityConversionResponse = ActivityConversionResponse.getDataFromIntent(intent);
  9.                List<ActivityConversionData> list = activityConversionResponse .getActivityConversionDatas();
  10.            }
  11.        }
  12.    }
  13. }

3. 地理围栏服务开发步骤

要使用华为地理围栏服务API,需要确保您的设备已经下载并安装了HMS Core(APK),并将相关的SDK集成到您的项目中。有关详细信息,请参阅开发准备。

3.1 指定应用权限

1、如果需要使用地理围栏服务API,需要在Manifest文件中申请ACCESS_FINE_LOCATION权限:

  1. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

2、在Android Q版本中,需要在Manifest文件中申请ACCESS_BACKGROUND_LOCATION权限:

  1. <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

3.2 创建地理围栏服务客户端

在Activity的OnCreate()方法中创建GeofenceService实例,并使用该实例调用与geofence相关的API接口。

  1. private GeofenceService geofenceService;
  2. private ArrayList<String> idList;
  3. private ArrayList<Geofence> geofenceList;
  4. private String TAG;
  5. //获取PendingIntent及回调结果的方式可自定义,这里以广播为例进行说明
  6. private PendingIntent pendingIntent;
  7. protected void onCreate(Bundle savedInstanceState) {    
  8.    geofenceService = LocationServices.getGeofenceService(this);
  9.    pendingIntent = getPendingIntent();
  10.    idList = new ArrayList<String>();
  11.    geofenceList = new ArrayList<Geofence>();
  12.    TAG = "geoFence";
  13. }

3.3 创建并添加地理围栏

您可以先创建地理围栏实例,并构建添加地理围栏的请求。在发送请求之后,会通过Task通知您是否添加成功。

1、创建地理围栏实例

  1. geofenceList.add(new Geofence.Builder()    
  2.                 .setUniqueId("mGeofence")    
  3.                 .setValidContinueTime(10000)    
  4.                 //传入经纬度信息,圆形地理围栏半径(单位:米)
  5.                 .setRoundArea(latitude, longitude, radius)    
  6.                 //进入或退出围栏时触发回调
  7.                 .setConversions(Geofence.ENTER_GEOFENCE_CONVERSION | Geofence.EXIT_GEOFENCE_CONVERSION)    
  8.                 .build());
  9. idList.add("mGeofence");

2、创建添加地理围栏的请求

  1. private GeofenceRequest getAddGeofenceRequest() {    
  2.    GeofenceRequest.Builder builder = new GeofenceRequest.Builder();    
  3.    //当用户在围栏中时,添加围栏后立即触发回调
  4.    builder.setInitConversions(GeofenceRequest.ENTER_INIT_CONVERSION);    
  5.    builder.createGeofenceList(geofenceList);    
  6.    return builder.build();
  7. }

3、新建pengdingIntent

  1. private PendingIntent getPendingIntent() {
  2.    //GeoFenceBroadcastReceiver类为自定义静态广播类,详细的实现方法可以参照示例代码。
  3.    Intent intent = new Intent(this, GeoFenceBroadcastReceiver.class);
  4.    intent.setAction(GeoFenceBroadcastReceiver.ACTION_PROCESS_LOCATION);
  5.    return PendingIntent.getBroadcast(this,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  6. }

4、发送添加地理围栏请求

  1. public void requestGeoFenceWithNewIntent() {
  1.    geofenceService.createGeofenceList(getAddGeofenceRequest(), pendingIntent)
  2.        .addOnCompleteListener(new OnCompleteListener<Void>() {
  3.            @Override
  4.            public void onComplete(Task<Void> task) {
  5.                if (task.isSuccessful()) {
  6.                    Log.i(TAG, "add geofence success!");
  7.                } else {
  8.                    Log.w(TAG, "add geofence failed : " + task.getException().getMessage());
  9.                }
  10.            }
  11.        });
  1. }

5、移除地理围栏

  1. public void removeWithID() {
  2.    geofenceService.deleteGeofenceList(idList)
  3.        .addOnCompleteListener(new OnCompleteListener<Void>() {
  4.            @Override
  5.            public void onComplete(Task<Void> task) {
  6.                if (task.isSuccessful()) {
  7.                    Log.i(TAG, "delete geofence with ID success!");
  8.                } else {
  9.                    Log.w(TAG, "delete geofence with ID failed ");
  10.                }
  11.            }
  12.        });
  13. }

除了通过id移除地理围栏,您还可以通过pendingintent进行移除。

6、地理围栏触发信息处理

当检测到用户触发围栏事件时,会通过PendingIntent发送广播通知用户。

  1. public class GeoFenceBroadcastReceiver extends BroadcastReceiver {
  2.    public static final String ACTION_PROCESS_LOCATION = "com.huawei.hmssample.geofence.GeoFenceBroadcastReceiver.ACTION_PROCESS_LOCATION";
  3.    @Override
  4.    public void onReceive(Context context, Intent intent) {
  5.        if (intent != null) {
  6.            final String action = intent.getAction();
  7.            StringBuilder sb = new StringBuilder();
  8.            String next = "\n";
  9.            if (ACTION_PROCESS_LOCATION.equals(action)) {
  10.                GeofenceData geofenceData = GeofenceData.getDataFromIntent(intent);
  11.                if (geofenceData != null) {
  12.                   int errorCode = geofenceData.getErrorCode();
  13.                   int conversion = geofenceData.getConversion();
  14.                   List<Geofence> list = geofenceData.getConvertingGeofenceList();
  15.                   Location mLocation = geofenceData.getConvertingLocation();
  16.                   boolean status = geofenceData.isSuccess();
  17.                   sb.append("errorcode: " + errorCode + next);
  18.                   sb.append("conversion: " + conversion + next);
  19.                   for(int i = 0;i < list.size();i++){
  20.                       sb.append("geoFence id :" + list.get(i).getUniqueId() + next);
  21.                   }
  22.                   sb.append("location is :" + mLocation.getLongitude() + " " + mLocation.getLatitude() + next);
  23.                   sb.append("is successful :" + status);
  24.                   Log.i(TAG,sb.toString());
  25.                }
  26.            }
  27.        }
  28.    }
  29. }