[Huawei Developers] Freemind R:
Introduction

This article provides information to book any trip using Trip Booking Android app. It provides a solution for HMS based multiple kits such as Account Kit, Huawei Ads, Huawei Map Direction Polyline API, Huawei Location, Huawei Map, Huawei Awareness Weather API, and Huawei Analytics to use in Trip Booking.

The following HMS Kits used in this application:

1) Huawei Account Kit: Integrated this kit for login and logout.

2) Huawei Ads: Integrated this kit for better ads experiences so that users can find the better advertisements.

3) Huawei Analytics: Integrated this kit in this application for better analysis.

4) Huawei Map: Integrated this kit for better real time experience of trip booking so that user can identify the location of trip on map.

5) Huawei Direction API: Integrated this API for better trip booking experience such as users can identify the trip direction from his/her location on map.

6) Huawei Awareness Weather API: Integrated this API for weather forecast of trip.

7) Huawei Location: Integrated this Kit to get current location of user so that users can identify from current location to desire trip location.

Note: Refer to the previous articles.

1) Explore the world Trip Booking App, Part-1 login with Huawei ID

2) Explore the world Trip Booking App, Part-2 Ads and Analytics

3) Explore the world Trip Booking App, Part-3 Map and direction API

Prerequisite

1. A computer (desktop or laptop)

2. A Huawei phone, which is used to debug the developed app

3. HUAWEI Analytics Kit 5.0.3.

4. Android SDK applicable to devices using Android API-Level 19 (Android 4.4 KitKat) or higher.

5. Android Studio

6. Java JDK 1.7 or later (JDK 1.8 recommended).

Things Need To Be Done

To integrate HUAWEI HMS Core services, you must complete the following preparations:

1. Create an app in AppGallery Connect.

2. Create an Android Studio project.

3. Add the app package name and save the configuration file.

4. Configure the Maven repository address and AppGallery Connect gradle plug-in.

Weather Awareness API

HUAWEI Awareness Kit provides your app with the ability to obtain contextual information including users' current time, location, behavior, audio device status, ambient light, weather, and nearby beacons. Your app can gain insight into a user's current situation more efficiently, making it possible to deliver a smarter, more considerate user experience.

Integration process

1) Assigning Permissions in the Manifest File

2) Importing API Classes

3) Developing Capabilities

1) Assigning Permissions in the Manifest File

Before calling the weather awareness capability, assign required permissions in the manifest file.

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

2) Importing API Classes

To use the weather awareness capability, you need to import the public capability classes of Awareness Kit, and also the weather-related classes.

import com.huawei.hmf.tasks.OnFailureListener;import com.huawei.hmf.tasks.OnSuccessListener;import com.huawei.hms.kit.awareness.Awareness;
import com.huawei.hms.kit.awareness.status.WeatherStatus;
import com.huawei.hms.kit.awareness.status.weather.Situation;
import com.huawei.hms.kit.awareness.status.weather.WeatherSituation;

3) Developing Capabilities

Obtain the Capture Client object of Awareness Kit.

public class AwarenessWeather {

private static final String TAG = AwarenessWeather.class.getName();

public CurrentWeather.Current getWeatherSituation(Context context) {
CurrentWeather.Current current = new CurrentWeather().new Current();

Awareness.getCaptureClient(context).getWeatherByDevice()
.addOnSuccessListener(weatherStatusResponse -> {
WeatherStatus weatherStatus = weatherStatusResponse.getWeatherStatus();
WeatherSituation weatherSituation = weatherStatus.getWeatherSituation();
Situation situation = weatherSituation.getSituation();

String weatherInfoStr =
"Time Zone : " + (weatherSituation.getCity().getTimeZone()) + "\n\n" +
"Weather id : " + situation.getWeatherId() + "\n\n" +
"Temperature : " + situation.getTemperatureC() + "℃" +
"/" + situation.getTemperatureF() + "℉" + "\n\n" +
"Wind speed : " + situation.getWindSpeed() + "km/h" + "\n\n" +
"Wind direction : " + situation.getWindDir() + "\n\n" +
"Humidity : " + situation.getHumidity() + "%";
Log.i(TAG, weatherInfoStr);
current.setObservationTime("Day");
current.setTemperature(Math.toIntExact(situation.getTemperatureC()));
current.setIsDay(url);
})
.addOnFailureListener(e -> {
Log.e(TAG, "get weather failed");
});
return current;
}

}

Location Kit

HUAWEI Location Kit combines the GNSS, Wi-Fi, and base station location functionalities into your app to build up global positioning capabilities, allows you to provide flexible location-based services targeted at users around the globe. Currently, it provides three main capabilities: Fused location, Activity identification, and Geofence. You can call one or more of these capabilities as required.

1) Fused location: Provides a set of simple and easy-to-use APIs for your app to quickly obtain the device location based on the GNSS, Wi-Fi, and base station location data.

2) Activity identification: Identifies user motion status through the acceleration sensor, cellular network information, and magnetometer, help to adapt the app to user behavior.

3) Geofence: Allows you to set an interesting area through an API so that your app can receive a notification when a specified action (such as leaving, entering, or staying in the area) occurs.

Integration process

1) Add following dependency in Gradle File.

implementation 'com.huawei.hms:location:5.0.2.301

2) Assigning App Permissions.

Apply for location permissions in the AndroidManifest.xml file.

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

3) Creating a Location Service Client.

Create a FusedLocationProviderClient instance using the onCreate() method of Activity and use the instance to call location-related APIs.

private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest mLocationRequest;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
}

4) Check permission.

// check location permisiion
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);
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "onRequestPermissionsResult: apply LOCATION PERMISSION successful");
} else {
Log.i(TAG, "onRequestPermissionsResult: apply LOCATION PERMISSSION failed");
}
}

if (requestCode == 2) {
if (grantResults.length > 2 && grantResults[2] == PackageManager.PERMISSION_GRANTED
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "onRequestPermissionsResult: apply ACCESS_BACKGROUND_LOCATION successful");
} else {
Log.i(TAG, "onRequestPermissionsResult: apply ACCESS_BACKGROUND_LOCATION failed");
}
}
}

Huawei Map Direction API

Huawei Map provides Direction API so that user can access all the information related to Map in RESTful API.

Huawei has provided the following API endpoint to access Direction API.

https://mapapi.cloud.huawei.com/mapApi/v1

Huawei provides the following direction API:

1. Walking Route Planning

2. Bicycling Route Planning

3. Driving Route Planning

Implemented the Driving Route API with the help of Retrofit and MVVM.

Retrofit Client

Created MapApiClient class for accessing the Direction API.

public class MapApiClient {

private final static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
private static OkHttpClient okHttpClient;

public static Service getClient() {
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);

if (okHttpClient == null) {
okHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Consants.BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();

return retrofit.create(Service.class);
}

public interface Service {

@POST("mapApi/v1/routeService/driving")
Single<PolylineResponse> getPolylines(
@Query("key") String apiKey,
@Body PolylineBody polylineBody);

}
}

API Repository

I have created MapApiRepo class for accessing the API client.

public class MapApiRepo {
private MapApiClient.Service mService;

public MapApiRepo() {
this.mService = MapApiClient.getClient();
}

public Single<PolylineResponse> executeMapApi(PolylineBody polylineBody) {
return mService.getPolylines(Consants.API_KEY, polylineBody);
}
}

ViewModel

I have created MapApiViewModel class for handling the API calls.

public class MapApiViewModel extends ViewModel {

private final CompositeDisposable disposables = new CompositeDisposable();
private MapApiRepo mapApiRepo = new MapApiRepo();
private MutableLiveData<PolylineResponse> mPolylineLiveData = new MutableLiveData<>();

public LiveData<PolylineResponse> getPolylineLiveData(PolylineBody body) {
disposables.add(mapApiRepo.executeMapApi(body)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> mPolylineLiveData.setValue(result),
throwable -> mPolylineLiveData.setValue(null)
));
return mPolylineLiveData;
}

@Override
protected void onCleared() {
disposables.clear();
}
}

Drawing Polyline

I have implemented this functionality in the following activity.

mapApiViewModel.getPolylineLiveData(getPolylineBody()).observe(this, result -> {
Log.d(TAG, result.toString());
getPolylineData(result);
}); private PolylineBody getPolylineBody() {
PolylineBody polylineBody = new PolylineBody();
Origin origin = new Origin();
origin.setLat("30.0444");
origin.setLng("31.2357");

Destination destination = new Destination();
destination.setLat("30.0131");
destination.setLng("31.2089");

polylineBody.setDestination(destination);
polylineBody.setOrigin(origin);

return polylineBody;
}

public void getPolylineData(PolylineResponse polylineResponse) {
List<Routes> routesList = polylineResponse.getRoutes();
List<Paths> paths = new ArrayList<>();
List<Steps> steps = new ArrayList<>();
List<Polyline> polylines = new ArrayList<>();
latLngList = new ArrayList<>();

for (int x = 0; x < routesList.size(); x++) {
//here we can access each array list with main.get(x).
for (Paths paths1 : routesList.get(x).getPaths()) {
paths.add(paths1);
}
for (int y = 0; y < paths.size(); y++) {
for (Steps step :
paths.get(y).getSteps()) {
steps.add(step);
}
}
for (int i = 0; i < steps.size(); i++) {
for (Polyline polyline :
steps.get(i).getPolyline()) {
polylines.add(polyline);
}
}
}

for (int i = 0; i < polylines.size(); i++) {
latLngList.add(new LatLng(Double.valueOf(polylines.get(i).getLat())
, Double.valueOf(polylines.get(i).getLng())));
}

hmap.addPolyline(new PolylineOptions()
.addAll(latLngList)
.color(Color.BLUE)
.width(3));
}

App Development

Created the following package inside the project. In which integrated as Account Kit, Huawei Ads, Huawei Map Direction Polyline API, Huawei Location, Huawei Map, Huawei Awareness Weather API, and Huawei Analytics.

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/768/541/2640091000001768541.20200929070333.30716811684528093292261885352991:50511014010319:2800:CB40E6AA156EA28EA9BD26450BCB2897C080C38985222BD756C229829FF88597.png"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/768/541/2640091000001768541.20200929070333.30716811684528093292261885352991:50511014010319:2800:CB40E6AA156EA28EA9BD26450BCB2897C080C38985222BD756C229829FF88597.png[/IMG]

PolyLineActivity

In this activity, I have integrated Location kit, Map, and Direction API.

Launch the application

Let us launch our application, see the result

[IMG="https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/768/541/2640091000001768541.20200925090828.67726625066315674866261568103816:50511014010319:2800:5CFC38C1DFD60A93F701A07BC0A1DDE263BA3BC08CDB5528A768107C30D472DE.gif"]https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/001/768/541/2640091000001768541.20200925090828.67726625066315674866261568103816:50511014010319:2800:5CFC38C1DFD60A93F701A07BC0A1DDE263BA3BC08CDB5528A768107C30D472DE.gif[/IMG]

If you have any doubts or queries. Leave your valuable comment in the comment section and do not forget to like and follow me

Conclusion

In this article, I have explained how to integrate Location Kit and Weather Awareness in Trip Booking application and draw a route between origins to destination.

References

Driving Direction API:

https://developer.huawei.com/consumer/en/doc/development/HMSCore-References-V5/directions-driving-0000001050161496-V5