[Huawei Developers] shikkerimath:
Besides the usual offerings of flowers and handbags, what other ways are there to profess your love for your girlfriend?

John, a programmer at Huawei, provides us with a novel answer. John is currently on a business trip in France and wanted to do something different to show his appreciation for his girlfriend, who is far away in China, on March 8th – International Women's Day.

Looking out of his hotel window at the Eiffel Tower, an idea struck John's mind: What if I make an exercise tracking app to express my feelings for her? He shared the fruits of his quick labor with his girlfriend, who saw the following image when she opened the app:

View attachment 5251703

On March 8th, we present you with this special tutorial on how to use HUAWEI Location Kit to win the heart of that special person in your life as well as imbue your apps with powerful location services.

Overview​

HUAWEI Location Kit can combine the GNSS, Wi-Fi, and base station positioning capabilities into your app, allowing you to provide flexible location-based services for users around the world. We also provide HUAWEI Map Kit, which is an SDK for map development that includes map data for more than 200 countries and regions across the globe, and supports over 100 languages. With this SDK, you can display your user's exercise routes on a map in real time through the use of various map display tools.

Besides being a creative way of expressing your feeling for someone, exercise tracking can be applied to a wide range of scenarios. For example, it provides health and fitness apps with location-based services, such as recording exercise routes, displaying past exercise routes, and calculating distance traveled, so that users can track how much exercise they've done and calculate how many calories they've burned.

Development Preparations​

1. Create an app in AppGallery Connect and configure the signing certificate fingerprint.

2. Configure the Maven repository address and add the following build dependencies to the build.gradle file in the app directory.

dependencies {
implementation 'com.huawei.hms:location: 5.1.0.301'
implementation 'com.huawei.hms:maps: 5.1.0.300'
}

3. Configure obfuscation scripts.

For details about the preceding steps, please refer to the Location Kit Development Guide on the HUAWEI Developers website.

4. Declare system permissions in the AndroidManifest.xml file.

Location Kit incorporates GNSS, Wi-Fi, and base station positioning capabilities into your app so that you can provide precise global positioning services for your users. In order to do this, it requires the network permission, precise location permission, and coarse location permission. If you want the app to continuously obtain user locations when running in the background, you also need to declare the ACCESS_BACKGROUND_LOCATION permission in the AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

Development Procedure​

1. Displaying the Map​

Currently, the HMS Core Map SDK supports two map containers: SupportMapFragment and MapView. This article uses SupportMapFragment as an example.

(1) Add a Fragment object in the layout file (for example, activity_main.xml), and set map attributes in the file.

<fragment
android:id="@+id/mapfragment_routeplanningdemo"
android:name="com.huawei.hms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

(2) To use a map in your app, implement the OnMapReadyCallback API.

RoutePlanningActivity extends AppCompatActivity implements OnMapReadyCallback

(3) In the code file (for example, MainActivity.java), load SupportMapFragment in the onCreate() method and call getMapAsync() to register the callback.

Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.mapfragment_routeplanningdemo);
if (fragment instanceof SupportMapFragment) {
SupportMapFragment mSupportMapFragment = (SupportMapFragment) fragment;
mSupportMapFragment.getMapAsync(this);
}(4) Call the onMapReady callback to obtain the HuaweiMap object.
@Override
public void onMapReady(HuaweiMap huaweiMap) {

hMap = huaweiMap;
hMap.setMyLocationEnabled(true);
hMap.getUiSettings().setMyLocationButtonEnabled(true);
}

2. Implementing the Location Function​

(1) Check the location permission.

XXPermissions.with(this)
// Apply for multiple permissions.
.permission(Permission.Group.LOCATION)
.request(new OnPermission() {
@Override
public void hasPermission(List<String> granted, boolean all) {
if (all) {
getMyLoction();
} else{
Toast.makeText(getApplicationContext(),"The function may be unavailable if the permissions are not assigned.",Toast.LENGTH_SHORT).show();
}
}
@Override
public void noPermission(List<String> denied, boolean never) {
if (never) {
XXPermissions.startPermissionActivity(RoutePlanningActivity.this, denied);
} else {
XXPermissions.startPermissionActivity(RoutePlanningActivity.this, denied);
}
}
});

(2) Pinpoint the current location and display it on the map. You need to check whether the location permission is enabled. If not, the location data cannot be obtained.

SettingsClient settingsClient = LocationServices.getSettingsClient(this);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check the device location settings.
settingsClient.checkLocationSettings(locationSettingsRequest)
.addOnSuccessListener(locationSettingsResponse -> {
// Initiate location requests when the location settings meet the requirements.
fusedLocationProviderClient
.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
.addOnSuccessListener(aVoid -> {
// Processing when the API call is successful.
Log.d(TAG, "onSuccess: " + aVoid);
});
})
.addOnFailureListener(e -> {
// Device location settings do not meet the requirements.
int statusCode = ((ApiException) e).getStatusCode();
if (statusCode == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
try {
ResolvableApiException rae = (ResolvableApiException) e;
// Call startResolutionForResult to display a popup message requesting the user to enable relevant permissions.
rae.startResolutionForResult(RoutePlanningActivity.this, 0);
} catch (IntentSender.SendIntentException sie) {
sie.printStackTrace();
}
}
});

3. Drawing Routes on the Map Based on the Real-time Location​

private void addPath(LatLng latLng1, LatLng latLng2) {
PolylineOptions options = new PolylineOptions().color(Color.BLUE).width(5);
List<LatLng> path = new ArrayList<>();
path.add(latLng1);
path.add(latLng2);
for (LatLng latLng : path) {
options.add(latLng);
}
Polyline polyline = hMap.addPolyline(options);
mPolylines.add(polyline);
}Upload the location results to the cloud in real time by using the route planning function of Map Kit. The routes will then be returned and displayed on the map.String mWalkingRoutePlanningURL = "https://mapapi.cloud.huawei.com/mapApi/v1/routeService/walking";
String url = mWalkingRoutePlanningURL + "?key=" + key;

Response response = null;
JSONObject origin = new JSONObject();
JSONObject destination = new JSONObject();
JSONObject json = new JSONObject();
try {
origin.put("lat", latLng1.latitude);
origin.put("lng", latLng1.longitude);

destination.put("lat", latLng2.latitude);
destination.put("lng", latLng2.longitude);

json.put("origin", origin);
json.put("destination", destination);

RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
Request request = new Request.Builder().url(url).post(requestBody).build();
response = getNetClient().initOkHttpClient().newCall(request).execute();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;

Results​

Once the code is compiled, an APK will be generated. Install it on your device and launch the app. Exercise tracks can now be drawn on the map based on your real-time location information.

More Information

To join in on developer discussion forums, go to Reddit.

To download the demo app and sample code, go to GitHub.

For solutions to integration-related issues, go to Stack Overflow.

Checkout in forum