Integration of Huawei Account Kit, Ads Kit, Location Kit and Map Kit in Locate

Song Jie
9 min readOct 7, 2021

--

Hello all, this article is regarding how to develop this Locate with a few Huawei Kits including Account Kit, Ads Kit, Map Kit and Location Kit. This app provides powerful location search which has 190 million POIs, 570 million addresses, 80 million postcodes, and 690,000 administrative divisions (Levels 1–9) of massive location data. Besides, Locate enables users to interact with the map through gestures and buttons in different scenarios. Users are able to check their own device’s location with the exact latitude and longitude results shown in the app.

This app will only be available on Huawei AppGallery.

Thanks to all the Huawei mentors and seniors for the guidance and lesson given!!

Basic Features of the App/Use Case:

Users are able to identify their own location anytime and anywhere as long as there is internet available. They adjust the map size through gestures by zooming or minimizing the map and get the exact longitude, latitude with the accuracy of results by clicking a simple button. Users are also able to remove their location callback result with clicking the button.

Link to the Application:

Account Kit:

Huawei Account Kit provides one-click sign-in which allows HUAWEI ID holders to sign into the app using HUAWEI IDs, without having to go through the registration. After sign-in, an easy SMS verification which lets the app get SMS codes either automatically or when authorized. With this Account Kit, users from a wide range of devices (phones, tablets, smart displays etc) can connect it easily as it provides all-scenario access.

Ads Kit:

Huawei Ads Kit provides unique advertising IDs that enable developers to operate easily with third-party advertising and tracking platforms while safeguarding user privacy for high-quality and targeted adverts in app.

Location Kit:

Huawei Location Kit provides a fused location function which intelligently combines GNSS Wi-Fi, and base stations to precise users’ location.

Map Kit:

Huawei Map Kit provides location-based services which makes the app better while the map presentation and interaction are customized.

Development Environment

Android Studio version: 3.x or later

JDK version: 1.8 or later

SDK and Gradle:

-If you need to use multiple HMS Core kits, use the latest versions required for these kits.

-Test device: a Huawei phone running EMUI 3.0 or later, or a non-Huawei phone running Android 4.4 or later

Prerequisite:

  • Register to Huawei Developers to access HMS Core Kits
  • Create a project in the Huawei AppGallery Connect.
  • Create SHA-256 Key for your application.
  • Make sure the required kits (Account, Ads Kit, Map Kit and Location Kit) are allowed in the Manage API section.
  • Download and paste the agconnect.json file in your application under App Folder.
  • After creating the application in the AppGallery Connect,let us move to the integration part.

Integration (Getting Started)

  1. In the project level build.gradle copy and paste the following code:
buildscript {repositories {google()jcenter()// Configure the Maven repository address for the HMS Core SDK.maven {url 'https://developer.huawei.com/repo/'}}dependencies {...// Add the AppGallery Connect plugin configuration.classpath 'com.huawei.agconnect:agcp:1.4.2.300'}}allprojects {repositories {google()jcenter()// Configure the Maven repository address for the HMS Core SDK.maven {url 'https://developer.huawei.com/repo/'}}}

2. In the app level build.gradle copy and paste the following code:

plugins {id 'com.android.application'// Add the following configuration:id 'com.huawei.agconnect'}

3. The Account SDK requires permissions to obtain the network status and Wi-Fi status. Declare the permissions in the AndroidManifest.xml file as follows:

<manifest ...>...<!--check network permissions--><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><!--check wifi state--><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />...</manifest>

Implementation of Account Kit

  1. Integrate HMS Core SDK by using Maven repository and add the AppGallery Connect Configuration File into the app.
  2. Adding Permissions
  3. Scenario-based Development
  • Signing-in
  • Implement Huawei ID sign-in button in layout
<!-- Define an ID for the button control. →<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButtonandroid:id="@+id/HuaweiIdAuthButton"android:layout_width="wrap_content"android:layout_height="wrap_content"/>
  • Implement Huawei ID sign-in function
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// activity_main is the name of the custom layout file.setContentView(R.layout.activity_main);findViewById(R.id.HuaweiIdAuthButton).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {silentSignInByHwId();}});}
  • Process sign-in result to obtain ID information( Sign-in without Identity verification)
@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == REQUEST_CODE_SIGN_IN) {Log.i(TAG, "onActivitResult of sigInInIntent, request code: " + REQUEST_CODE_SIGN_IN);Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);if (authAccountTask.isSuccessful()) {// The sign-in is successful, and the authAccount object that contains the HUAWEI ID information is obtained.AuthAccount authAccount = authAccountTask.getResult();dealWithResultOfSignIn(authAccount);Log.i(TAG, "onActivitResult of sigInInIntent, request code: " + REQUEST_CODE_SIGN_IN);} else {// The sign-in fails. Find the failure cause from the status code. For more information, please refer to the "Error Codes" section in the API Reference.Log.e(TAG, "sign in failed : " +((ApiException)authAccountTask.getException()).getStatusCode());}}}

Implementation of Ads Kit

  1. Integrating the HUAWEI Ads SDK (com.huawei.hms:ads) into the app.
  2. Banner ads is the format type that is chosen.
  3. Add banner view.
  • Edit XML Layout file with following code:
BannerView bannerView = findViewById(R.id.hw_banner_view);
  • Add BannerView to the XML layout file, and set hwads:adId to the ad unit ID and hwads:bannerSize to ad dimensions. The following sample code shows how to add BannerView to an XML layout file:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res-auto"xmlns:hwads="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"><com.huawei.hms.ads.banner.BannerViewandroid:id="@+id/hw_banner_view"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_centerHorizontal="true"hwads:adId="testw6vs28auh3"hwads:bannerSize="BANNER_SIZE_360_57"/></RelativeLayout>
  • Use coding.Add BannerView to the code, and set the ad unit ID and ad dimensions.
BannerView bannerView = new BannerView(this);// "testw6vs28auh3" is a dedicated test ad unit ID. Before releasing your app, replace the test ad unit ID with the formal one.bannerView.setAdId("testw6vs28auh3");bannerView.setBannerAdSize(BannerAdSize.BANNER_SIZE_360_57);FrameLayout adFrameLayout = findViewById(R.id.ad_frame);adFrameLayout.addView(bannerView);
  • After adding BannerView, load an ad using the loadAd() method in the BannerView class.
...import com.huawei.hms.ads.AdParam;import com.huawei.hms.ads.BannerAdSize;import com.huawei.hms.ads.banner.BannerView;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// Obtain BannerView.BannerView bannerView = findViewById(R.id.hw_banner_view);// Set the ad unit ID and ad dimensions. "testw6vs28auh3" is a dedicated test ad unit ID.bannerView.setAdId("testw6vs28auh3");bannerView.setBannerAdSize(BannerAdSize.BANNER_SIZE_360_57);// Set the refresh interval to 30 seconds.bannerView.setBannerRefresh(30);// Create an ad request to load an ad.AdParam adParam = new AdParam.Builder().build();bannerView.loadAd(adParam);}}

Implementation of Location Kit

  1. Developing the fused location service
  • Assigning App Permission
<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" />
  • After applying for permissions in the AndroidManifest.xml file, apply for the permissions dynamically in the code (according to requirements for dangerous permissions in Android 6.0 or later).
// Dynamically apply for required permissions if the API level is 28 or lower.if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {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 {// Dynamically apply for the android.permission.ACCESS_BACKGROUND_LOCATION permission in addition to the preceding permissions if the API level is higher than 28.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);}}

2. Create a FusedLocationProviderClient instance using the onCreate() method of the location service activity in your project, and use the instance to call location-related APIs.

// Define a FusedLocationProviderClient object.private FusedLocationProviderClient fusedLocationProviderClient;// Define a location request object.private LocationRequest mLocationRequest;protected void onCreate(Bundle savedInstanceState) {fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);}

3. Check Location Settings

SettingsClient settingsClient = LocationServices.getSettingsClient(this);LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();mLocationRequest = new LocationRequest();builder.addLocationRequest(mLocationRequest);LocationSettingsRequest locationSettingsRequest = builder.build();// Check the device location settings.settingsClient.checkLocationSettings(locationSettingsRequest)// Define the listener for success in calling the API for checking device location settings..addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {@Overridepublic void onSuccess(LocationSettingsResponse locationSettingsResponse) {LocationSettingsStates locationSettingsStates =locationSettingsResponse.getLocationSettingsStates();StringBuilder stringBuilder = new StringBuilder();// Checks whether the location function is enabled.stringBuilder.append(",\nisLocationUsable=").append(locationSettingsStates.isLocationUsable());// Checks whether HMS Core (APK) is available.stringBuilder.append(",\nisHMSLocationUsable=").append(locationSettingsStates.isHMSLocationUsable());Log.i(TAG, "checkLocationSetting onComplete:" + stringBuilder.toString());}})// Define callback for failure in checking the device location settings..addOnFailureListener(new OnFailureListener() {@Overridepublic void onFailure(Exception e) {// Processing when the device is a Huawei device and has HMS Core (APK) installed, but its settings do not meet the location requirements.int statusCode = ((ApiException) e).getStatusCode();switch (statusCode) {case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:try {ResolvableApiException rae = (ResolvableApiException) e;// Call startResolutionForResult to display a popup asking the user to enable related permission.rae.startResolutionForResult(MainActivity.this, 0);} catch (IntentSender.SendIntentException sie) {// TODO}break;}}});

4. Continuously obtaining the device location

a. Set parameters for continuously requesting device locations:

LocationRequest mLocationRequest = new LocationRequest();// Set the location update interval (unit: ms).mLocationRequest.setInterval(10000);// Set the location type.mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

b. Define the location update callback:

LocationCallback mLocationCallback;mLocationCallback = new LocationCallback() {@Overridepublic void onLocationResult(LocationResult locationResult) {if (locationResult != null) {// Process the location callback result.}}};

c. Call requestLocationUpdates() for continuous location:

fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper()).addOnSuccessListener(new OnSuccessListener<Void>() {@Overridepublic void onSuccess(Void aVoid) {// Processing when the API call is successful.}}).addOnFailureListener(new OnFailureListener() {@Overridepublic void onFailure(Exception e) {// Processing when the API call fails.}});

d. Call removeLocationUpdates() to stop requesting location updates:

// Note: When requesting location updates is stopped, mLocationCallback must be the same object as LocationCallback in the requestLocationUpdates method.fusedLocationProviderClient.removeLocationUpdates(mLocationCallback)// Define callback for success in stopping requesting location updates..addOnSuccessListener(new OnSuccessListener<Void>() {@Overridepublic void onSuccess(Void aVoid) {// TODO}})// Define callback for failure in stopping requesting location updates..addOnFailureListener(new OnFailureListener() {@Overridepublic void onFailure(Exception e) {// TODO}});

Implementation of Map Kit

  1. Create Map Instance
  • Add a fragment element into the layout file and set attributes in the file
<fragment xmlns:android="http://schemas.android.com/apk/res/android"xmlns:map="http://schemas.android.com/apk/res-auto"android:id="@+id/mapfragment_mapfragmentdemo"class="com.huawei.hms.maps.SupportMapFragment"android:layout_width="match_parent"android:layout_height="match_parent"map:cameraTargetLat="48.893478"map:cameraTargetLng="2.334595"map:cameraZoom="10" />
  • Implement OnMapReadyCallback API in app
public class SupportMapDemoActivity extends AppCompatActivity implements OnMapReadyCallback {...}
  • Load SupportMapFragment in the onCreate() method and call getMapAsync() to register the callback.
private SupportMapFragment mSupportMapFragment;mSupportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapfragment_mapfragmentdemo);mSupportMapFragment.getMapAsync(this);
  • Call the onMapReady callback to obtain the HuaweiMap object.
public void onMapReady(HuaweiMap huaweiMap) {Log.d(TAG, "onMapReady: ");hMap = huaweiMap;}

2. Get current locations

  • Declare permissions
<!-- Allow the app to obtain the coarse longitude and latitude of a user through the Wi-Fi network or base station. --><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/><!-- Allow the app to receive location information from satellites through the GPS chip. --><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
  • Apply it in code(according to requirements for dangerous permissions in Android 6.0).
// If the API level is 23 or higher (Android 6.0 or later), you need to dynamically apply for permissions.if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {Log.i(TAG, "sdk >= 23 M");// Check whether your app has the specified permission and whether the app operation corresponding to the permission is allowed.if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED|| ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {// Request permissions for your app.String[] strings ={Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};// Request permissions.ActivityCompat.requestPermissions(this, strings, 1);}}
  • Call the setMyLocationEnabled(true) method of the HuaweiMap object to enable the my-location function.
@RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})@Overridepublic void onMapReady(HuaweiMap map){hMap = map;// Enable the my-location layer.hMap.setMyLocationEnabled(true);// Enable the my-location icon.hMap.getUiSettings().setMyLocationButtonEnabled(true);}

Results:

Real time screenshot of application

Conclusion:

In conclusion, Huawei HMS Core has a wide range of open device and cloud features that allow for quick development, expansion, and monetization options. Hence, HMS Core Kits has offered our team a lot of flexibility in developing apps and also ensure that a good and quality user experience is provided to end users. For instance, not only the basic Account Kit developed in the apps but also adding Ads Kit, Location Kit and Map Kit to deliver next-level user experiences, and make premium content and services broadly accessible. As a final point, hopefully every user will find our app and article useful.

--

--