关于android:HMS-Core定位服务在生活服务类App中可以自动填写收货地址啦

42次阅读

共计 5962 个字符,预计需要花费 15 分钟才能阅读完成。

在波及团购、外卖、快递、家政、物流、搬家等生存服务类的 App、小程序中,填写收货地址是用户高频应用的性能。这一性能通常采取让用户手动填写的解决方案,例如高低拉动抉择浙江省 –> 杭州市 –> 西湖区 –> 西溪街道,再切换到姓名输入框输出姓名 –> 电话输入框输出电话等一系列的操作。从中咱们不难发现手动输出地址不仅费时费力,而且一不小心还会呈现选错地址的景象。

那有没有什么办法能帮忙用户又快又精确的填写地址呢?借助 HMS Core 定位服务的交融定位 + 天文编码能力,生存服务类 App 能够主动定位获取用户以后地位信息或某地的行政区划信息、街道信息,并精确填写至地址栏中。用户无需本人手动输出,缩小了操作工夫,并且不必再放心填错地址。以下是咱们提供的示例代码,开发者们依照步骤尝试,就能够轻松体验这个性能啦~

成果展现

开发实战

开发步骤

一、开发筹备

1. 登录 AppGallery Connect 网站,点击“我的我的项目”。找到您的我的项目在 API 治理开启 location 开关, 在我的项目中点击须要配置签名证书指纹的利用。在“我的项目设置 > 惯例”页面的“利用”区域,点击“SHA256 证书指纹”后的“增加证书指纹”,输出生成的 SHA256 指纹。

2. 在“我的项目设置 > 惯例”页面的“利用”区域,点击“agconnect-services.json”下载配置文件。将“agconnect-services.json”文件拷贝到利用级根目录下。

3. 我的项目级“build.gradle”文件

buildscript {
    repositories {google()
        jcenter()
        maven {url 'https://developer.huawei.com/repo/'}
        mavenCentral()}
    dependencies {
        classpath 'com.android.tools.build:gradle:4.1.2'
        classpath 'com.huawei.agconnect:agcp:1.6.0.300'
    }
}

allprojects {
    repositories {maven { url 'https://developer.huawei.com/repo/'}
        google()
        jcenter()
        mavenCentral()}
}

利用级的“build.gradle”文件

plugins {
    id 'com.android.application'
    id 'com.huawei.agconnect'
}

在“dependencies”中增加如下编译依赖

implementation 'com.huawei.hms:location:6.3.0.300'

二、权限查看

1. 在“AndroidManifest.xml”文件中配置权限 ACCESS_COARSE_LOCATION(粗略的地位权限),ACCESS_FINE_LOCATION(准确的地位权限)和 ACCESS_BACKGROUND_LOCATION 权限

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

2. 动静申请定位相干权限(Android 6.0 及以上版本危险权限要求)

    Log.i(TAG, "android 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 = {Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                "android.permission.ACCESS_BACKGROUND_LOCATION"};
        ActivityCompat.requestPermissions(this, strings, 2);
    }
}

三、获取定位后果

1. 设置定位参数,包含地位更新的距离,定位类型等

mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
mSettingsClient = LocationServices.getSettingsClient(this);
mLocationRequest = new LocationRequest();
// Sets the interval for location update (unit: Millisecond)
mLocationRequest.setInterval(5000);
// Sets the priority
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

2. 调用 getSettingsClient() 接口获取 SettingsClient 实例。调用调用 checkLocationSettings() 查看设施开关设置

LocationSettingsRequest locationSettingsRequest = builder.build();
// Before requesting location update, invoke checkLocationSettings to check device settings.
Task<LocationSettingsResponse> locationSettingsResponseTask =
        mSettingsClient.checkLocationSettings(locationSettingsRequest);

查看开关开启之后,调用 requestLocationUpdates() 进行定位

locationSettingsResponseTask.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
    @Override
    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {Log.i(TAG, "check location settings success");
        mFusedLocationProviderClient
                .requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {Log.i(TAG, "requestLocationUpdatesWithCallback onSuccess");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(Exception e) {Log.e(TAG, "requestLocationUpdatesWithCallback onFailure:" + e.getMessage());
                    }
                });
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(Exception e) {Log.e(TAG, "checkLocationSetting onFailure:" + e.getMessage());
        int statusCode = 0;
        if (e instanceof ApiException) {statusCode = ((ApiException) e).getStatusCode();}
        switch (statusCode) {
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                try {
                    // When the startResolutionForResult is invoked, a dialog box is displayed, asking you
                    // to open the corresponding permission.
                    if (e instanceof ResolvableApiException) {ResolvableApiException rae = (ResolvableApiException) e;
                        rae.startResolutionForResult(MainActivity.this, 0);
                    }
                } catch (IntentSender.SendIntentException sie) {Log.e(TAG, "PendingIntent unable to execute request.");
                }
                break;
            default:
                break;
        }
    }
});

四、逆天文编码获取以后地位

胜利获取定位信息的经纬度之后,将经纬度信息传递给应用天文编码服务(GeocoderService)取得天文编码申请对象,而后调用申请逆天文编码方法(getFromLocation),设置申请(GetFromLocationRequest)参数,获取逆天文编码信息回调。

if (null == mLocationCallback) {mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {if (locationResult != null) {List<Location> locations = locationResult.getLocations();
                if (!locations.isEmpty()) {ExecutorUtil.getInstance().execute(new Runnable() {
                        @Override
                        public void run() {Locale locale = new Locale("zh", "CN");
                            GeocoderService geocoderService = LocationServices.getGeocoderService(MainActivity.this, locale);
                            GetFromLocationRequest getFromLocationRequest = new GetFromLocationRequest(locations.get(0).getLatitude(), locations.get(0).getLongitude(), 1);
                            geocoderService.getFromLocation(getFromLocationRequest)
                                    .addOnSuccessListener(new OnSuccessListener<List<HWLocation>>() {
                                        @Override
                                        public void onSuccess(List<HWLocation> hwLocation) {printGeocoderResult(hwLocation);
                                        }
                                    })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(Exception e) {Log.i(TAG, e.getMessage());
                                        }
                                    });
                        }
                    });
                }
            }
        }
        @Override
        public void onLocationAvailability(LocationAvailability locationAvailability) {if (locationAvailability != null) {boolean flag = locationAvailability.isLocationAvailable();
                Log.i(TAG, "onLocationAvailability isLocationAvailable:" + flag);
            }
        }
    };
}

最初将获取到的结果显示在界面上即可。

理解更多详情 >>

拜访华为开发者联盟官网
获取开发领导文档
华为挪动服务开源仓库地址:GitHub、Gitee

关注咱们,第一工夫理解 HMS Core 最新技术资讯~

正文完
 0