[Huawei Developers] Freemind R:
More articles like this, you can visit HUAWEI Developer Forum​

Hello everyone, in this article we’re going to take a look at the Awareness Kit features so we can easily put these features to our apps.

Providing dynamic and effective user experiences to the app is an important point. Huawei Awareness Kit allows this to be done quickly and economically.It has collection of both contextual and location based features such as users’ current time, location, behavior, audio device status, ambient light, weather, and nearby beacons.

Huawei Awareness Kit also strongly emphasizes both the power and memory consumption when accessing these features and helping to ensure that the battery life and memory usage of your apps.

To use these features, Awareness Kit has two different sections:

Capture API

The Capture API allows your app to request the current user status, such as time, location, behavior, and whether a headset is connected.

Barrier API

The Barrier API allows your app to set a combination of contextual conditions. When the preset contextual conditions are met, your app will receive a notification.

I created a sample app which I’ve open-sourced on GitHub for enthusiasts who want to use this kit.

Setting up the Awareness Kit

You’ll need to do setup before you can use the Awareness Kit.You can follow the official documentation on how to prepare app on App Gallery Connect.

Add the required dependencies to the build.gradle file under app folder.We need awareness and location kit dependencies.

implementation 'com.huawei.hms:awareness:1.0.3.300'
implementation 'com.huawei.hms:location:4.0.4.300'

Add the required permissions to the AndroidManifest.xml file under app/src/main folder.

<!-- Location permission, which is sensitive. After the permission is declared, you need to dynamically apply for it in the code. -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- Location permission. If only the IP address-based time capture function is used, you can declare only this permission. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- If your app uses the barrier capability and runs on Android 10 or later, you need to add the background location access permission, which is also a sensitive permission. -->
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" /> <!-- Behavior detection permission (Android 10 or later). This permission is sensitive and needs to be dynamically applied for in the code after being declared. -->
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" /> <!-- Behavior detection permission (Android 9). This permission is sensitive and needs to be dynamically applied for in the code after being declared. -->
<uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />

Don’t forget checking permissions in the app.

Checking location permission:

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_REQUEST_ACCESS_FINE_LOCATION)
return
}

Capture API

Firstly, We’re going to examine the Capture API in depth.This API allows us to request the current user status from current environment.Using this API we can retrieve data such as:

Obtains the current local time or time of a specified location, such as working day, weekend, etc.

Getting the users’ current location.

Obtains the current activity behavior, such as walking, running, cycling, driving, or staying still.

Indicates whether the device has approached, connected to, or disconnected from a registered beacon.

Retrieve info related to the user currently has their headphones plugged in or unplugged.

Obtains the status of an audio device (connected or disconnected).

Obtains the illuminance of the environment in lux unit where the device is located.

The weather status based on where the user is currently located.

Let’s take a deep look at these different awarenesses that we can retrieve from the Capture API.

Time Awareness

Using the Capture API we can detect whether the holiday information of most countries/regions and sunrise and sunset time of all cities around the world. Some simple use cases could be found in:

A meditation app that wishes to show a notification to remind morning rest

A gift card sending app that may wish to send virtual holiday wish cards to users

To obtain the time categories from the Capture API we simply need to call the timeCategories method.This will return instance of the TimeCategoriesResponse class that if successful, will contain information about the time categories as integer array.

private fun getTimeCategories() {

try {
// Use getTimeCategories() to get the information about the current time of the user location.
// Time information includes whether the current day is a workday or a holiday, and whether the current day is in the morning, afternoon, or evening, or at the night.
val task = Awareness.getCaptureClient(this).timeCategories
task.addOnSuccessListener { timeCategoriesResponse ->
val timeCategories = timeCategoriesResponse.timeCategories
// do anything with time categories array

}.addOnFailureListener { e ->
Toast.makeText(
applicationContext, "get Time Categories failed",
Toast.LENGTH_SHORT
).show()
Log.e(TAG, "get Time Categories failed", e)
}
} catch (e: Exception) {
logViewTv.text = "get Time Categories failed.Exception:" + e.message
}
}

[IMG="https://miro.medium.com/max/332/1*2uqCvuqUZdJMa4mzdRPIKg.jpeg"]https://miro.medium.com/max/332/1*2uqCvuqUZdJMa4mzdRPIKg.jpeg[/IMG]

Location Awareness

Using the Capture API we can get location information where the user currently is. Some simple use cases could be found in:

A shopping app can show their nearby stores in current user location if there is.

An event app can show the upcoming events based on the appropriate location.

To get the location from the Capture API we simply need to call the location method.This will return instance of the LocationResponse class that if successful, will contain information about the users current location includes latitude, longitude, accuracy and altitude.

private fun getLocation(){

Awareness.getCaptureClient(this).location
.addOnSuccessListener { locationResponse ->
val location: Location = locationResponse.location

val latitude = location.latitude
val longitude = location.longitude
val accuracy = location.accuracy
val altitude = location.altitude

}
.addOnFailureListener {
logViewTv.text = "get location failed:" + it.message
}
}

Behavior Awareness

We can use the Capture API to detect the current activity behavior. Some simple use cases could be found in:

A fitness app can log user activity in background and make a graph from this data

An ebook listening app that wishes to recommend listening book when user is walking.

To get the current user behavior from the Capture API we simply need to call the behavior method.This will return instance of the BehaviorResponse class that if successful, will contain information about the users current context.

private fun getUserBehavior(){

Awareness.getCaptureClient(this).behavior
.addOnSuccessListener { behaviorResponse ->

val behaviorStatus = behaviorResponse.behaviorStatus
val mostLikelyBehavior = behaviorStatus.mostLikelyBehavior
val mostLikelyBehaviors = behaviorStatus.probableBehavior
val mostProbableActivity = mostLikelyBehavior.type

val detectedBehavior: Long = behaviorStatus.time

val elapsedTime: Long = behaviorStatus.elapsedRealtimeMillis

}
.addOnFailureListener {
logViewTv.text = "get behavior failed: " + it.message
}
}

Beacon Awareness

We can use the Capture API to get registered beacons in nearby. You need to register beacon devices with your project. For details, please refer to Beacon Management. Some simple use cases could be found in:

When the user enters a store, the application can show a special discount to the person.

A bus app that wishes to show push notifications about buses going in that direction.

To get any nearby registered beacons from the Capture API we simply need to call the getBeaconStatus method. This will return instance of the BeaconStatusResponse class that if successful, will contain information about nearby registered beacons.

private fun getBeacons(){
val namespace = "sample namespace"
val type = "sample type"
val content = byteArrayOf(
's'.toByte(),
'a'.toByte(),
'm'.toByte(),
'p'.toByte(),
'l'.toByte(),
'e'.toByte()
)
val filter = BeaconStatus.Filter.match(namespace, type, content)
Awareness.getCaptureClient(this).getBeaconStatus(filter)
.addOnSuccessListener { beaconStatusResponse ->
val beaconDataList = beaconStatusResponse.beaconStatus.beaconData
if (beaconDataList != null && beaconDataList.size != 0) {
var i = 1
val builder = StringBuilder()
for (beaconData in beaconDataList) {
builder.append("Beacon Data ").append(i)
builder.append(" namespace:").append(beaconData.namespace)
builder.append(",type:").append(beaconData.type)
builder.append(",content:").append(Arrays.toString(beaconData.content))
builder.append("; ")
i++
}

} else {
logViewTv.text = "no beacons match filter nearby"
}
}
.addOnFailureListener { e ->
logViewTv.text = "get beacon status failed: " + e.message
}
}

Headset Awareness

Using the Capture API we can get information about headphones connected. Some simple use cases could be found in:

A music app stop playing song on their app when the user disconnects their headphones.

An ebook listening app can show a notification to allow quick access to their app when the user connects their headphones.

To obtain the headphone status from the Capture API we simply need to call the headsetStatus method .This will return instance of the HeadsetStatusResponse class that if successful, will contain information about the devices current headphone status.

[IMG="https://miro.medium.com/max/332/1*zpdGW6s_zjfHFCVC7IcU2A.jpeg"]https://miro.medium.com/max/332/1*zpdGW6s_zjfHFCVC7IcU2A.jpeg[/IMG]

Bluetooth Car Stereo Awareness

Using the Capture API we can get information about bluetooth car stereo connected. Some simple use cases could be found in:

A music app that wishes to show a notification to play a song when the car stereo connects.

A radio app that wishes to ask playing a radio when the car stereo connects.

To get the car stereo status from the Capture API we simply need to call the getBluetoothStatus method .This will return instance of the BluetoothStatusResponse class that if successful, will contain information about the car stereo status.

private fun getCarStereoStatus() {
val deviceType = 0 // Value 0 indicates a Bluetooth car stereo.

Awareness.getCaptureClient(this).getBluetoothStatus(deviceType)
.addOnSuccessListener { bluetoothStatusResponse ->
val bluetoothStatus = bluetoothStatusResponse.bluetoothStatus
val status = bluetoothStatus.status
val stateStr = "The Bluetooth car stereo is " + if (status == BluetoothStatus.CONNECTED) "connected" else "disconnected"

}
.addOnFailureListener { e ->
logViewTv.text = "get bluetooth status failed: " + e.message
}
}

Ambient Light Awareness

Using the Capture API we can obtain information about ambient light. Some simple use cases could be found in:

A book reading application can adjust the brightness of the screen according to the ambient light to consider the eyesight.

A video watching application can adjust the brightness of the screen according to the ambient light to consider the eyesight.

To get the ambient light from the Capture API we simply need to call the lightIntensity method .This will return instance of the AmbientLightResponse class that if successful, will contain information about the ambient light as lux.

private fun getAmbientLight() {
Awareness.getCaptureClient(this).lightIntensity
.addOnSuccessListener { ambientLightResponse ->
val ambientLightStatus = ambientLightResponse.ambientLightStatus

logViewTv.text = "Light intensity is " + ambientLightStatus.lightIntensity + " lux"
}
.addOnFailureListener { e ->
logViewTv.text = "get light intensity failed" + e.message
}
}

[IMG="https://miro.medium.com/max/332/1*Mg9QYrA9OPOfGBrDykPJNw.jpeg"]https://miro.medium.com/max/332/1*Mg9QYrA9OPOfGBrDykPJNw.jpeg[/IMG]

Weather Awareness

We can also use the Capture API to retrieve the weather status of where the user is currently located. Some simple use cases could be found in:

A music app can recommend a playlist to listen to, depending on the weather.

A fitness app can give a weather alert to users before running outside.

To get the weather status from the Capture API we simply need to call the weatherByDevice method .This will return instance of the WeatherStatusResponse class that if successful.

private fun getWeather(){

Awareness.getCaptureClient(this).weatherByDevice
.addOnSuccessListener { weatherStatusResponse ->
val weatherStatus = weatherStatusResponse.weatherStatus
val weatherSituation = weatherStatus.weatherSituation
val situation = weatherSituation.situation

cityNameTv.text = "City: " + weatherSituation.city.name
weatherIdTv.text = "Weather id is: " + situation.weatherId
cnWeatherIdTv.text = "CN Weather id is: " + situation.cnWeatherId
temperatureCTv.text = "Temperature is: " + situation.temperatureC + "℃"
temperatureFTv.text = "Temperature is: " + situation.temperatureF + "℉"
windSpeedTv.text = "Wind speed is: " + situation.windSpeed
windDirectionTv.text = "Wind direction is: " + situation.windDir
humidityTv.text = "Humidity is : " + situation.humidity

}
.addOnFailureListener {
logViewTv.text = "get weather failed: " + it.message
}
}

[IMG="https://miro.medium.com/max/332/1*4RT7ADwmRh7pWGd39ZLzDA.jpeg"]https://miro.medium.com/max/332/1*4RT7ADwmRh7pWGd39ZLzDA.jpeg[/IMG]