[Huawei Developers] muraliameakula:
Introduction

In this article, we will learn how to implement Huawei Awareness kit features with Local Notification service to send notification when certain condition met. We can create our own conditions to be met and observe them and notify to the user even when the application is not running.

The Awareness Kit is quite a comprehensive detection and event SDK. If you're developing a context-aware app for Huawei devices, this is definitely the library for you.

What can we do using Awareness kit?

With HUAWEI Awareness Kit, you can obtain a lot of different contextual information about users’ location, behavior, weather, current time, device status, ambient light, audio device status and makes it easier to provide more refined user experience.

Basic Usage

There are quite a few awareness "modules" in this SDK: Time Awareness, Location Awareness, Behavior Awareness, Beacon Awareness, Audio Device Status Awareness, Ambient Light Awareness, and Weather Awareness. Read on to find out how and when to use them.

Each of these modules has two modes: capture, which is an on-demand information retrieval; and barrier, which triggers an action when a specified condition is met.

Use case

The Barrier API allows us to set specific barriers for specific conditions in our app and when these conditions are satisfies, our app will be notified, so we could take action based on our conditions. In this sample, when user starts the activity and app notifies to the user “please connect the head set to listen music” while doing activity.

Table of content

1. Project setup

2. Headset capture API

3. Headset Barrier API

4. Flutter Local notification plugin

Advantages

1. Converged: Multi-dimensional and evolvable awareness capabilities can be called in a unified manner.

2. Accurate: The synergy of hardware and software makes data acquisition more accurate and efficient.

3. Fast: On-chip processing of local service requests and nearby access of cloud services promise a faster service response.

4. Economical: Sharing awareness capabilities avoids separate interactions between apps and the device, reducing system resource consumption. Collaborating with the EMUI (or Magic UI) and Kirin chip, Awareness Kit can even achieve optimal performance with the lowest power consumption.

Requirements

1. Any operating system(i.e. MacOS, Linux and Windows)

2. Any IDE with Flutter SDK installed (i.e. IntelliJ, Android Studio and VsCode etc.)

3. A little knowledge of Dart and Flutter.

4. A Brain to think

5. Minimum API Level 24 is required.

6. Required EMUI 5.0 and later version devices.

Setting up the Awareness kit

1. Firstly create a developer account in AppGallery Connect. After create your developer account, you can create a new project and new app. For more information check this link.

2. Generating a Signing certificate fingerprint, follow below command.

keytool -genkey -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks
-storepass <store_password> -alias <alias> -keypass<key_password> -keysize 2048 -keyalg RSA -validity 36500

3. The above command creates the keystore file in appdir/android/app.

4. Now we need to obtain the SHA256 key, follow the command.

keytool -list -v -keystore <application_project_dir>\android\app\<signing_certificate_fingerprint_filename>.jks

5. Enable the Awareness kit in the Manage API section and add the plugin.

6. After configuring project, we need to download agconnect-services.json file in your project and add into your project.

7. After that follow the URL for cross-platform plugins. Download required plugins.

8. The following dependencies for HMS usage need to be added to build.gradle file under the android directory.

buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}
}

dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'http://developer.huawei.com/repo/'}

}
}

9. Then add the following line of code to the build.gradle file under the android/app directory.

apply plugin: 'com.huawei.agconnect'

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

<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" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

11. After completing all the above steps, you need to add the required kits’ Flutter plugins as dependencies to pubspec.yaml file. You can find all the plugins in pub.dev with the latest versions.

huawei_awareness:
path: ../huawei_awareness/

12. To display local notification, we need to add flutter local notification plugin.

flutter_local_notifications: ^3.0.1+6

After adding them, run flutter pub get command. Now all the plugins are ready to use.

Note: Set multiDexEnabled to true in the android/app directory, so that app will not crash.

Code Implementation

Use Capture and Barrier API to get Headset status

This service will helps in your application before starting activity, it will remind you to connect the headset to play music.

We need to request the runtime permissions before calling any service.

@override
void initState() {
checkPermissions();
requestPermissions();
super.initState();
}

void checkPermissions() async {
locationPermission = await AwarenessUtilsClient.hasLocationPermission();
backgroundLocationPermission =
await AwarenessUtilsClient.hasBackgroundLocationPermission();
activityRecognitionPermission =
await AwarenessUtilsClient.hasActivityRecognitionPermission();
if (locationPermission &&
backgroundLocationPermission &&
activityRecognitionPermission) {
setState(() {
permissions = true;
notifyAwareness();
});
}
}

void requestPermissions() async {
if (locationPermission == false) {
bool status = await AwarenessUtilsClient.requestLocationPermission();
setState(() {
locationPermission = status;
});
}

if (backgroundLocationPermission == false) {
bool status =
await AwarenessUtilsClient.requestBackgroundLocationPermission();
setState(() {
locationPermission = status;
});
}

if (activityRecognitionPermission == false) {
bool status =
await AwarenessUtilsClient.requestActivityRecognitionPermission();
setState(() {
locationPermission = status;
});
checkPermissions();
}
}

Capture API: Now all the permissions are allowed, once app launched if we want to check the headset status, then we need to call the Capture API using getHeadsetStatus(), only one time this service will cal.

checkHeadsetStatus() async {
HeadsetResponse response = await AwarenessCaptureClient.getHeadsetStatus();
setState(() {
switch (response.headsetStatus) {
case HeadsetStatus.Disconnected:
_showNotification(
"Music", "Please connect headset before start activity");
break;
}
});
log(response.toJson(), name: "captureHeadset");
}

Barrier API: If you want to set some conditions into your app, then we need to use Barrier API. This service keep on listening event once satisfies the conditions automatically it will notifies to user. for example we mentioned some condition like we need to play music once activity starts, now user connects the headset automatically it will notifies to the user headset connected and music playing.

First we need to set barrier condition, it means the barrier will triggered when conditions satisfies.

String headSetBarrier = "HeadSet";
AwarenessBarrier headsetBarrier = HeadsetBarrier.keeping(
barrierLabel: headSetBarrier, headsetStatus: HeadsetStatus.Connected);

Add the barrier using updateBarriers() this method will return whether barrier added or not.

bool status =await AwarenessBarrierClient.updateBarriers(barrier: headsetBarrier);

If status returns true it means barrier successfully added, now we need to declare StreamSubscription to listen event, it will keep on update the data once condition satisfies it will trigger.

if(status){
log("Headset Barrier added.");
StreamSubscription<dynamic> subscription;
subscription = AwarenessBarrierClient.onBarrierStatusStream.listen((event) {
if (mounted) {
setState(() {
switch (event.presentStatus) {
case HeadsetStatus.Connected:
_showNotification("Cool HeadSet", "Headset Connected,Want to listen some music?");
isPlaying = true;
print("Headset Status: Connected");
break;
case HeadsetStatus.Disconnected:
_showNotification("HeadSet", "Headset Disconnected, your music stopped");
print("Headset Status: Disconnected");
isPlaying = false;
break;
case HeadsetStatus.Unknown:
_showNotification("HeadSet", "Your headset Unknown");
print("Headset Status: Unknown");
isPlaying = false;
break;
}
});
}
}, onError: (error) {
log(error.toString());
});
}else{
log("Headset Barrier not added.");
}

Need of Local Push Notification?

1. We can Schedule notification.

2. No web request is required to display Local notification.

3. No limit of notification per user.

4. Originate from the same device and displayed on the same device.

5. Alert the user or remind the user to perform some task.

This package provides us the required functionality of Local Notification. Using this package we can integrate our app with Local Notification in android and ios app both.

Add the following permission to integrate your app with the ability of scheduled notification.

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

Add inside application.

<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />

Let’s create Flutter local notification object.

FlutterLocalNotificationsPlugin localNotification = FlutterLocalNotificationsPlugin();

@override
void initState() {
// TODO: implement initState
super.initState();
var initializationSettingsAndroid =
AndroidInitializationSettings('ic_launcher');
var initializationSettingsIOs = IOSInitializationSettings();
var initSetttings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOs);
localNotification.initialize(initSetttings);
}

Now create logic for display simple notification.

Future _showNotification(String title, String description) async {
var androidDetails = AndroidNotificationDetails(
"channelId", "channelName", "content",
importance: Importance.high);
var iosDetails = IOSNotificationDetails();
var generateNotification =
NotificationDetails(android: androidDetails, iOS: iosDetails);
await localNotification.show(
0, title, description, generateNotification);
}

Demo

Tips and Tricks

1. Download latest HMS Flutter plugin.

2. Set minSDK version to 24 or later.

3. HMS Core APK 4.0.2.300 is required.

4. Currently this plugin not supporting background task.

5. Do not forget to click pug get after adding dependencies.

Conclusion

In this article, we have learned how to use Barrier API of Huawei Awareness Kit with a Local Notification to observe the changes in environmental factors even when the application is not running.

As you may notice, the permanent notification indicating that the application is running in the background is not dismissible by the user which can be annoying.

Based on requirement we can utilize different APIs, Huawei Awareness Kit has many other great features that we can use with foreground services in our applications.

Thanks for reading! If you enjoyed this story, please click the Like button and Follow. Feel free to leave a Comment 💬 below.

Reference

Awareness Kit URL.

Awareness Capture API Article URL.

Original Source