要使用华为定位服务API,需要确保您的设备已经下载并安装了HMS Core服务组件,并将相关的SDK集成到您的项目中。有关详细信息,请参阅开发准备。
1、Android提供了两种位置权限: ACCESS_COARSE_LOCATION(粗略的位置权限) 和ACCESS_FINE_LOCATION(精确的位置权限)。需要在Manifest文件中申请权限:
- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
2、在Android Q版本中,如果您需要应用程序在后台执行时也具备持续定位能力,需要在Manifest文件中申请ACCESS_BACKGROUND_LOCATION权限:
- <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
3、在Manifest中添加后,还要在代码中动态申请一下权限(Android 6.0危险权限要求):
- if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
- Log.i(TAG, "sdk < 28 Q");
- if (ActivityCompat.checkSelfPermission(this,
- Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
- || ActivityCompat.checkSelfPermission(this,
- Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- String[] strings =
- {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
- ActivityCompat.requestPermissions(this, strings, 1);
- }
- } else {
- if (ActivityCompat.checkSelfPermission(this,
- Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
- || ActivityCompat.checkSelfPermission(this,
- Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
- || ActivityCompat.checkSelfPermission(this,
- "android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED) {
- String[] strings = {android.Manifest.permission.ACCESS_FINE_LOCATION,
- android.Manifest.permission.ACCESS_COARSE_LOCATION,
- "android.permission.ACCESS_BACKGROUND_LOCATION"};
- ActivityCompat.requestPermissions(this, strings, 2);
- }
- }
在Activity的OnCreate()方法中创建一个FusedLocationProviderClient实例,通过该实例调用定位相关接口。
- private FusedLocationProviderClient fusedLocationProviderClient;
- private LocationRequest mLocationRequest;
- protected void onCreate(Bundle savedInstanceState) {
- fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
- }
设备的相关定位设置会影响华为定位服务的定位结果,例如位置开关选项处于关闭状态时,将无法获取到位置信息。因此,建议您在持续获取位置信息之前,先检查设备设置是否满足定位条件。华为定位服务提供了检查设备定位相关设置的能力,通过LocationServices的getSettingsClient(Activity activity)获取SettingsClient实例,然后调用checkLocationSettings( LocationSettingsRequest locationSettingsRequest)接口获取定位设置结果,当设置不满足定位条件时,将为您提供解决方案以提示用户打开对应的权限(HMS Core 定位权限必须打开,Android Q版本必须选择“始终允许”)。
1、获取SettingsClient的服务接口
- SettingsClient settingsClient = LocationServices.getSettingsClient(this);
2、调用checkLocationSettings()检查设备设置
- LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
- mLocationRequest = new LocationRequest();
- builder.addLocationRequest(mLocationRequest);
- LocationSettingsRequest locationSettingsRequest = builder.build();
- //检查设备定位设置
- settingsClient.checkLocationSettings(locationSettingsRequest)
- .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
- @Override
- public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
- //设置满足定位条件,再发起位置请求
- fusedLocationProviderClient
- .requestLocationUpdates(mLocationRequest, mLocationCallback,Looper.getMainLooper())
- .addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- //接口调用成功的处理
- }
- });
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- //设置不满足定位条件
- int statusCode = ((ApiException) e).getStatusCode();
- switch (statusCode) {
- case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
- try {
- ResolvableApiException rae = (ResolvableApiException) e;
- //调用startResolutionForResult可以弹窗提示用户打开相应权限
- rae.startResolutionForResult(MainActivity.this, 0);
- } catch (IntentSender.SendIntentException sie) {
- //…
- }
- break;
- }
- }
- });
如果您希望应用可以持续获取设备位置,可以使用华为定位服务提供的requestLocationUpdates()接口。该接口根据入参形式的不同,将以两种不同的形式将位置信息返回。一种是通过调用您已经定义的LocationCallback.onLocationResult()回调方法返回一个包含位置信息的LocationResult对象,另一种是将位置信息置于Pendingintent扩展信息中返回。
当您的应用程序不再需要接收位置更新时,应当停止位置更新,以便于降低功耗。要停止位置更新,可以调用removeLocationUpdates(),传入与requestLocationUpdates()接口相对应的LocationCallback或Pendingintent对象。这里以回调方式作为样例,代码如下。详细的参数说明见location接口说明。
1、设置持续定位请求参数
- LocationRequest mLocationRequest = new LocationRequest();
- //设置位置更新的间隔(毫秒为单位)
- mLocationRequest.setInterval(10000);
- //设置权重
- mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
2、定义位置更新回调
- LocationCallback mLocationCallback;
- mLocationCallback = new LocationCallback() {
- @Override
- public void onLocationResult(LocationResult locationResult) {
- if (locationResult != null) {
- //处理位置回调结果
- }
- }
- };
3、调用requestLocationUpdates()进行持续定位
- fusedLocationProviderClient
- .requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
- .addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- //接口调用成功的处理
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- //接口调用失败的处理
- }
- });
4、调用removeLocationUpdates()停止位置更新
- //注意:停止位置更新时,mLocationCallback必须与requestLocationUpdates方法中的LocationCallback参数为同一对象。
- fusedLocationProviderClient.removeLocationUpdates(mLocationCallback)
- .addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- //停止位置更新成功
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- //停止位置更新失败
- }
- });
使用华为定位服务API,您的应用程序可以获取设备最后的已知位置,大多情况下,该位置即为设备的当前位置。调用getLastLocation()方法获取最后的已知位置的代码样例如下:
- Task<Location> task = fusedLocationProviderClient.getLastLocation()
- .addOnSuccessListener(new OnSuccessListener<Location>() {
- @Override
- public void onSuccess(Location location) {
- if (location == null) {
- return;
- }
- //Location对象的处理逻辑
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- //异常处理逻辑
- }
- });
具体操作步骤:打开设置 -> 系统和更新 -> 开发人员选项 -> 选择模拟位置信息应用 -> 选择要mock的应用(如果没有发现“开发人员选项”,请执行如下操作:设置 -> 关于手机 -> 版本号,连续点击"版本号"7次,"开发人员选项"会出现在"系统与更新"页面,再重复上述操作),示例代码如下:
1、设置mock模式,调用setMockMode(boolean isMockMode)。
- fusedLocationProviderClient.setMockMode(mockFlag)
- .addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- Log.i(TAG, "setMockMode onSuccess");
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- Log.i(TAG, "setMockMode onFailure:" + e.getMessage());
- }
- });
2、设置模拟位置信息,调用setMockLocation(Location mockLocation)。
- fusedLocationProviderClient.setMockLocation(mockLocation)
- .addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- Log.i(TAG, "setMockLocation onSuccess");
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- Log.i(TAG, "setMockLocation onFailure:" + e.getMessage());
- }
- });
要使用华为活动识别服务API,需要确保您的设备已经下载并安装了HMS Core(APK),并将相关的SDK集成到您的项目中。有关详细信息,请参阅开发准备。以下仅为代码片段,详情请参考完整示例代码
1、在Android Q以下版本使用活动识别需要在manifest文件中配置以下权限:
- <uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION"/>
2、在Android Q及以上版本中,需要在Manifest文件中申请以下权限:
- <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
在Activity的OnCreate()方法中创建一个ActivityIdentificationService实例,通过该实例调用活动识别相关接口:
- //获取PendingIntent及回调结果的方式可自定义,这里以广播为例进行说明
- private PendingIntent pendingIntent;
- private ActivityIdentificationService activityIdentificationService;
- protected void onCreate(Bundle savedInstanceState) {
- activityIdentificationService = ActivityIdentification.getService(this);
- pendingIntent = getPendingIntent();
- };
使用活动识别服务,首先需要您注册活动识别更新,可以检测用户当前是步行,骑自行车,静止等状态。
1、新建PendingIntent
- private PendingIntent getPendingIntent() {
- //LocationBroadcastReceiver类为自定义静态广播类,详细的实现方法可以参照示例代码。
- Intent intent = new Intent(this, LocationBroadcastReceiver.class);
- intent.setAction(LocationBroadcastReceiver.ACTION_PROCESS_LOCATION);
- return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
- }
2、监听活动识别更新请求
通过调用createActivityIdentificationUpdates(long detectionIntervalMillis, PendingIntent pendingIntent)方法,第一个参数为更新的周期,第二个参数pendingIntent。
- activityIdentificationService.createActivityIdentificationUpdates(5000, pendingIntent)
- .addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- Log.i(TAG, "createActivityIdentificationUpdates onSuccess");
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- Log.e(TAG, "createActivityIdentificationUpdates onFailure:" + e.getMessage());
- }
- });
3、移除活动识别更新
在使用完活动识别后需要进行移除操作,移除活动识别定时监听,参数PendingIntent必须与createActivityIdentificationUpdates (long detectionIntervalMillis, PendingIntent callbackIntent)参数里的PendingIntent是同一个。
- activityIdentificationService.deleteActivityIdentificationUpdates(pendingIntent)
- .addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- Log.i(TAG, "deleteActivityIdentificationUpdates onSuccess");
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- Log.e(TAG, "deleteActivityIdentificationUpdates onFailure:" + e.getMessage());
- }
- });
4、活动识别结果获取
通过Pendingintent获取活动识别结果。
- public class LocationBroadcastReceiver extends BroadcastReceiver {
- public static final String ACTION_PROCESS_LOCATION = "com.huawei.hms.location.ACTION_PROCESS_LOCATION";
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent != null) {
- final String action = intent.getAction();
- if (ACTION_PROCESS_LOCATION.equals(action)) {
- ActivityIdentificationResponse activityIdentificationResponse = ActivityIdentificationResponse.getDataFromIntent(intent);
- List<ActivityIdentificationData> list = activityIdentificationResponse .getActivityIdentificationDatas();
- }
- }
- }
- }
接口提供检测活动过渡条件(进入,退出)的功能,例如需要检测用户从走路变为骑自行车的状态时,应用通过调用createActivityConversionUpdates(request, pendingIntent)方法获取活动过渡的状态变化。
1、设置监听活动过渡请求参数
- int STILL = 103;
- ActivityConversionInfo activityConversionInfo1 = new ActivityConversionInfo(STILL, ActivityConversionInfo.ENTER_ACTIVITY_CONVERSION);
- ActivityConversionInfo activityConversionInfo2 = new ActivityConversionInfo(STILL, ActivityConversionInfo.EXIT_ACTIVITY_CONVERSION);
- List<ActivityConversionInfo> activityConversionInfos = new ArrayList<>();
- activityConversionInfos.add(activityConversionInfo1);
- activityConversionInfos.add(activityConversionInfo2);
- ActivityConversionRequest request = new ActivityConversionRequest();
- request.setActivityConversions(activityConversionInfos);
2、监听活动过渡更新
- Task<Void> task = activityIdentificationService.createActivityConversionUpdates(request, pendingIntent);
- task.addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- Log.i(TAG, "createActivityConversionUpdates onSuccess");
- }
- }).addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- Log.e(TAG, "createActivityConversionUpdates onFailure:" + e.getMessage());
- }
- });
3、移除活动过渡更新
不需要监听活动过渡条件时,需要调用deleteActivityConversionUpdates(PendingIntent pendingIntent)进行移除操作。
- activityIdentificationService.deleteActivityConversionUpdates(pendingIntent)
- .addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- Log.i(TAG, "deleteActivityConversionUpdates onSuccess");
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(Exception e) {
- Log.e(TAG, "deleteActivityConversionUpdates onFailure:" + e.getMessage());
- }
- });
4、返回结果获取
活动过渡的结果
- public class LocationBroadcastReceiver extends BroadcastReceiver {
- public static final String ACTION_PROCESS_LOCATION = "com.huawei.hms.location.ACTION_PROCESS_LOCATION";
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent != null) {
- final String action = intent.getAction();
- if (ACTION_PROCESS_LOCATION.equals(action)) {
- ActivityConversionResponse activityConversionResponse = ActivityConversionResponse.getDataFromIntent(intent);
- List<ActivityConversionData> list = activityConversionResponse .getActivityConversionDatas();
- }
- }
- }
- }
要使用华为地理围栏服务API,需要确保您的设备已经下载并安装了HMS Core(APK),并将相关的SDK集成到您的项目中。有关详细信息,请参阅开发准备。
1、如果需要使用地理围栏服务API,需要在Manifest文件中申请ACCESS_FINE_LOCATION权限:
- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
2、在Android Q版本中,需要在Manifest文件中申请ACCESS_BACKGROUND_LOCATION权限:
- <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
在Activity的OnCreate()方法中创建GeofenceService实例,并使用该实例调用与geofence相关的API接口。
- private GeofenceService geofenceService;
- private ArrayList<String> idList;
- private ArrayList<Geofence> geofenceList;
- private String TAG;
- //获取PendingIntent及回调结果的方式可自定义,这里以广播为例进行说明
- private PendingIntent pendingIntent;
- protected void onCreate(Bundle savedInstanceState) {
- geofenceService = LocationServices.getGeofenceService(this);
- pendingIntent = getPendingIntent();
- idList = new ArrayList<String>();
- geofenceList = new ArrayList<Geofence>();
- TAG = "geoFence";
- }
3.3 创建并添加地理围栏
您可以先创建地理围栏实例,并构建添加地理围栏的请求。在发送请求之后,会通过Task通知您是否添加成功。
1、创建地理围栏实例
- geofenceList.add(new Geofence.Builder()
- .setUniqueId("mGeofence")
- .setValidContinueTime(10000)
- //传入经纬度信息,圆形地理围栏半径(单位:米)
- .setRoundArea(latitude, longitude, radius)
- //进入或退出围栏时触发回调
- .setConversions(Geofence.ENTER_GEOFENCE_CONVERSION | Geofence.EXIT_GEOFENCE_CONVERSION)
- .build());
- idList.add("mGeofence");
2、创建添加地理围栏的请求
- private GeofenceRequest getAddGeofenceRequest() {
- GeofenceRequest.Builder builder = new GeofenceRequest.Builder();
- //当用户在围栏中时,添加围栏后立即触发回调
- builder.setInitConversions(GeofenceRequest.ENTER_INIT_CONVERSION);
- builder.createGeofenceList(geofenceList);
- return builder.build();
- }
3、新建pengdingIntent
- private PendingIntent getPendingIntent() {
- //GeoFenceBroadcastReceiver类为自定义静态广播类,详细的实现方法可以参照示例代码。
- Intent intent = new Intent(this, GeoFenceBroadcastReceiver.class);
- intent.setAction(GeoFenceBroadcastReceiver.ACTION_PROCESS_LOCATION);
- return PendingIntent.getBroadcast(this,0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
- }
4、发送添加地理围栏请求
- public void requestGeoFenceWithNewIntent() {
- geofenceService.createGeofenceList(getAddGeofenceRequest(), pendingIntent)
- .addOnCompleteListener(new OnCompleteListener<Void>() {
- @Override
- public void onComplete(Task<Void> task) {
- if (task.isSuccessful()) {
- Log.i(TAG, "add geofence success!");
- } else {
- Log.w(TAG, "add geofence failed : " + task.getException().getMessage());
- }
- }
- });
- }
5、移除地理围栏
- public void removeWithID() {
- geofenceService.deleteGeofenceList(idList)
- .addOnCompleteListener(new OnCompleteListener<Void>() {
- @Override
- public void onComplete(Task<Void> task) {
- if (task.isSuccessful()) {
- Log.i(TAG, "delete geofence with ID success!");
- } else {
- Log.w(TAG, "delete geofence with ID failed ");
- }
- }
- });
- }
除了通过id移除地理围栏,您还可以通过pendingintent进行移除。
6、地理围栏触发信息处理
当检测到用户触发围栏事件时,会通过PendingIntent发送广播通知用户。
- public class GeoFenceBroadcastReceiver extends BroadcastReceiver {
- public static final String ACTION_PROCESS_LOCATION = "com.huawei.hmssample.geofence.GeoFenceBroadcastReceiver.ACTION_PROCESS_LOCATION";
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent != null) {
- final String action = intent.getAction();
- StringBuilder sb = new StringBuilder();
- String next = "\n";
- if (ACTION_PROCESS_LOCATION.equals(action)) {
- GeofenceData geofenceData = GeofenceData.getDataFromIntent(intent);
- if (geofenceData != null) {
- int errorCode = geofenceData.getErrorCode();
- int conversion = geofenceData.getConversion();
- List<Geofence> list = geofenceData.getConvertingGeofenceList();
- Location mLocation = geofenceData.getConvertingLocation();
- boolean status = geofenceData.isSuccess();
- sb.append("errorcode: " + errorCode + next);
- sb.append("conversion: " + conversion + next);
- for(int i = 0;i < list.size();i++){
- sb.append("geoFence id :" + list.get(i).getUniqueId() + next);
- }
- sb.append("location is :" + mLocation.getLongitude() + " " + mLocation.getLatitude() + next);
- sb.append("is successful :" + status);
- Log.i(TAG,sb.toString());
- }
- }
- }
- }
- }