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

HUAWEI Awareness Kit offers the Capture API and Barrier API.

What You Will Create

In this codelab, you will create an app that calls HUAWEI Awareness Kit.

What You Will Learn

Hardware Requirements

Software Requirements

HUAWEI HMS Core integration requires the following preparations

For details, see the HUAWEI HMS Core Integration Preparation.

If you are using Android Studio, you can integrate your HMS SDK by using the Maven repository. Before you start developing an app, integrate the HMS SDK into your Android Studio first.

Add the AppGallery Connect configuration file of the current app to your Android Studio.

  1. Sign in to AppGallery Connect and select My apps.
  2. Find your app from the list, and click the link under Android App in the Mobile phone column.
  3. Go to Develop > Overview > App information.
  4. Click agconnect-services.json to download the configuration file.
  5. Copy the agconnect-services.json file to the app's root directory.

Configure the Maven repository address for the HMS SDK.

  1. Open the build.gradle file in the root directory of your Android Studio project.
  2. Go to allprojects > repositories and configure the Maven repository address for the HMS SDK.
    allprojects { repositories { maven { url 'http://developer.huawei.com/repo/' } google() jcenter() } }
  3. Go to buildscript > repositories and configure the Maven repository address for the HMS SDK.
    buildscript { repositories { maven { url 'http://developer.huawei.com/repo/' } google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.3.0' } }
  4. Go to buildscript > dependencies and add dependency configurations.
    buildscript{ dependencies { classpath 'com.huawei.agconnect:agcp:' } }

Add build dependencies.

  1. Open the build.gradle file in the app directory.
  2. 在build.gradle文件中增加如下配置。
    compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 }
  3. Configure build dependencies under dependencies and replace {version} with the actual SDK version number, for example, implementation 'com.huawei.hms:awareness:'.
    dependencies{ implementation 'com.huawei.hms:awareness:{version}' }
  4. Add the AppGallery Connect plug-in dependency to the file header.
    apply plugin: 'com.huawei.agconnect'
  5. Open the modified build.gradle file again. You will find a Sync Now link in the upper right corner of the page. Click Sync Now and wait until synchronization is complete. If an error occurs, check the network connection and the configurations in the build.gradle file.

Before building the APK, configure obfuscation scripts to prevent the HMS SDK from being obfuscated. If obfuscation arises, the HMS SDK may not function properly.

  1. Open the obfuscation configuration file of your Android project.
  2. Add configurations to exclude the HMS SDK from obfuscation.
    -ignorewarnings -keepattributes *Annotation* -keepattributes Exceptions -keepattributes InnerClasses -keepattributes Signature -keepattributes SourceFile,LineNumberTable -keep class com.hianalytics.android.**{*;} -keep class com.huawei.updatesdk.**{*;} -keep class com.huawei.hms.**{*;}
  3. If you have used AndResGuard, add it to the whitelist in the obfuscation script file.
    "R.string.hms*", "R.string.connect_server_fail_prompt_toast", "R.string.getting_message_fail_prompt_toast", "R.string.no_available_network_prompt_toast", "R.string.third_app_*", "R.string.upsdk_*", "R.layout.hms*", "R.layout.upsdk_*", "R.drawable.upsdk*", "R.color.upsdk*", "R.dimen.upsdk*", "R.style.upsdk*", "R.string.agc*"

Assigning Permissions in the Manifest File

Before calling awareness capabilities, you need to assign required permissions in the manifest file. The permissions vary with awareness capabilities. For details, see the Development Guide.
For example, if you want to use the headset status awareness capability, enable Bluetooth on the device and assign the Bluetooth permission in the manifest file.

<!--Bluetooth permission --> <uses-permission android:name="android.permission.BLUETOOTH" />

Importing API Classes

You need to import appropriate capability API classes for calling different awareness capabilities. The class paths and names vary with capabilities. For details, see the API Reference.
For example, if you want to use the headset status awareness capability, import the public capability class of the awareness service and the headset status class.

import com.huawei.hmf.tasks.OnFailureListener; import com.huawei.hmf.tasks.OnSuccessListener; import com.huawei.hms.kit.awareness.Awareness; //import headset capture package import com.huawei.hms.kit.awareness.capture.HeadsetStatusResponse; import com.huawei.hms.kit.awareness.status.HeadsetStatus;

Developing Capture Capabilities

  1. Obtain the CaptureClient of HUAWEI Awareness Kit.
  2. Call the status query capability API through CaptureClient to query the context status.
  3. Enable your app to listen to the result returned by the awareness service for further processing. Example for headset status query:
    Awareness.getCaptureClient(this) .getHeadsetStatus() .addOnSuccessListener(new OnSuccessListener<HeadsetStatusResponse>() { @Override public void onSuccess(HeadsetStatusResponse headsetStatusResponse) { HeadsetStatus headsetStatus = headsetStatusResponse.getHeadsetStatus(); int status = headsetStatus.getStatus(); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.e("TAG",e.getMessage()); } });

Developing Barrier Capabilities

The following example illustrates how to develop the barrier for headset Connecting, which allows the barrier to trigger once headsets are connected.

  1. Define the barrier.
    AwarenessBarrier barrier = HeadsetBarrier.connecting();
  2. Define PendingIntent for the barrier, for example, to send a broadcast, and create a broadcast receiver to receive the broadcast.
    private PendingIntent mPendingIntent; private BarrierReceiver mBarrierReceiver; final String BARRIER_RECEIVER_ACTION = getApplication().getPackageName() + "BARRIER_RECEIVER_ACTION"; Intent intent = new Intent(BARRIER_RECEIVER_ACTION); mPendingIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); mBarrierReceiver = new BarrierReceiver(); registerReceiver(mBarrierReceiver, new IntentFilter(BARRIER_RECEIVER_ACTION));
  3. Add the barrier.
    String headsetBarrierLabel = "headsetheadset_connecting "; BarrierUpdateRequest.Builder builder = new BarrierUpdateRequest.Builder(); BarrierUpdateRequest request = builder.addBarrier(headsetBarrierKey,headsetBarrier,mPendingIntent).build(); Task<Void> task = Awareness.getBarrierClient(this).updateBarriers(request); task.addOnSuccessListener( new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(getApplicationContext(), "add barrier success", Toast.LENGTH_SHORT).show(); } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(Exception e) { Toast.makeText(getApplicationContext(), "add barrier failed", Toast.LENGTH_SHORT).show(); Log.e(TAG, "add barrier failed", e); } });
  4. Define the broadcast receiver to listen to the barrier event for further processing.
    class BarrierReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { BarrierStatus barrierStatus = BarrierStatus.extract(intent); String barrierLabel = barrierStatus.getBarrierKey(); switch(barrierStatus.getCurrentStatus()) { case BarrierStatus.TRUE: logView.println(barrierKey + " status:true"); break; case BarrierStatus.FALSE: logView.println(barrierKey + " status:false"); break; case BarrierStatus.UNKNOWN: logView.println(barrierKey + " status:unknown"); break; } } }

After you integrate the SDK, compare the log with the actual status to determine whether an API is called successfully. For example, if the log is "Headsets are unplugged" when you tap get Headset Status with no headsets plugged, the Capture API has been called successfully.

Well done. You have successfully completed this codelab and learned:

For more information about HUAWEI Awareness Kit, please visit our official website. If you encounter any problem during the development, see the FAQs.

For more information, please click the following links:

Download the demo source code used in this codelab from the following address:

Download source code

Code copied