More information like this, you can visit HUAWEI Developer Forum
INTERSTITIAL ADs
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Interstitial ads are full-screen ad formats that cover the interface of an app. They are usually displayed at natural transition points in the flow of an app like pausing a game or between different activities. The main difference between other types of ads and interstitial ads is that interstitial ones cover all the screen which makes it catchier and more effective.
Interstitial ads are used for high impression rate to increase downloads and revenue.
HUAWEI Ads Kit offers variety of different ads format to reach the consumer marketing goals in today’s competitive world.
HUAWEI Ads Kit provides easy and flexible way to implement the interstitial ads within your application.
Development Overview
HMS Ads KIT can be integrated for various business requirements in your react native project as following:
1. Perquisites
· Must have a Huawei Developer Account
· Must have a Huawei phone with HMS 4.0.0.300 or later
· React Native environment with Android Studio, Node Js and Visual Studio code.
2. Major Dependencies
· React Native CLI : 2.0.1
· Gradle Version: 6.0.1
· Gradle Plugin Version: 3.5.2
· React Native Site Kit SDK : 4.0.4
· React-native-hms-site gradle dependenc
· AGCP gradle dependency
3. Preparation
1. In order to develop the HMS react native apps following steps are mandatory.
2. Create an app or project in the Huawei app gallery connect.
3. Provide the SHA Key and App Package name of the project in App Information Section and enable the required API.
4. Create a react native project. Using
“react-native init project name”
5. Download the React Native Ads Kit SDK and paste it under Node Modules directory of React Native project.
· agconnect-services.json is not required for integrating the hms-ads-sdk.
· Run below command under project directory using CLI if you cannot find node modules.
Code:
“npm install” & “npm link”
4. Integration
1. Configure android level build.gradle
Add to buildscript/repositories and allprojects/repositories
Code:
maven {url 'http://developer.huawei.com/repo/'}
2. Configure app level build.gradle
Add to dependencies
Code:
Implementation project (“: react-native-hms-ads”)
3. Linking the HMS Ads Kit Sdk
Run below command in the project directory
Code:
react-native link react-native-hms-ads
5. Adding permissions
Add below permissions to Android.manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Development Process
Once sdk is integrated and ready to use, add following code to your App.js file which will import the API’s present.
· Creating an Interstitial Ad
· Setting Ad Slot ID
· Setting Ad Request Parameters (Optional)
· Loading the Ad
· Displaying the Ad
· Listening for Ad Events
· Testing
Creating an Interstitial Ad
HMSInterstitial module is used to create the interstitial Ad
Code:
import HMSAds, {
HMSInterstitial,
InterstitialMediaTypes,
} from 'react-native-hms-ads';
Setting Ad Slot ID
setAdId() method is responsible for setting the Ad Slot. Below is the code for same.
Developers can use publisher services to create the Ad Slot ID. Please refer this article to know the process for creating the slot Id’s
// creating object for the Ad Slot ID
Code:
const Interstitial = () => {
let interstitialAdIds = {};
interstitialAdIds[InterstitialMediaTypes.IMAGE] = 'teste9ih9j0rc3';
interstitialAdIds[InterstitialMediaTypes.VIDEO] = 'testb4znbuh3n2';
// creating object for setting up the media type for the ad
Code:
const [displayForm, setDisplayForm] = useState({
mediaType: InterstitialMediaTypes.VIDEO,
adId: interstitialAdIds.video,
// setting up the ID
Code:
HMSInterstitial.setAdId(displayForm.adId);
Setting Ad Request Parameters
setAsParam() method is used to set the parameters for the specific ad audience. Below code is called on the button click for the same.
Code:
import {ContentClassification,UnderAge } from 'react-native-hms-ads';
Code:
<Button
title="Set Ad Parameter"
onPress={() => {
HMSInterstitial.setAdParam({
adContentClassification:
ContentClassification.AD_CONTENT_CLASSIFICATION_UNKOWN,
// appCountry: '',
// appLang: '',
// belongCountryCode: '',
gender: Gender.UNKNOWN,
nonPersonalizedAd: NonPersonalizedAd.ALLOW_ALL,
// requestOrigin: '',
tagForChildProtection:
TagForChild.TAG_FOR_CHILD_PROTECTION_UNSPECIFIED,
tagForUnderAgeOfPromise: UnderAge.PROMISE_UNSPECIFIED,
// targetingContentUrl: '',
});
}}
/>
Loading the Ad
Calling the loadAd() method to load the ad on button click.
Code:
<Button
title="Load"
onPress={() => {
HMSInterstitial.loadAd();
}}
Displaying the Ad
isLoaded() method is called to confirm if the ad has finished loading.Once ad loading is completed, show() method is called to display the ad on a button click.
Code:
<Button
title="Show"
color="purple"
disabled={!isLoaded}
onPress={() => {
setLoaded(false);
HMSInterstitial.show();
}}
Listening for Ad Events
As we handle multiple Ad events for different actions, Listener is required for listening to these events as below.
Code:
useEffect(() => {
HMSInterstitial.setAdId(displayForm.adId);
HMSInterstitial.adClosedListenerAdd(() => {
toast('HMSInterstitial adClosed');
});
// HMSInterstitial.adClosedListenerRemove();
HMSInterstitial.adFailedListenerAdd((error) => {
toast('HMSInterstitial adFailed');
console.warn('HMSInterstitial adFailed, error: ', error);
});
// HMSInterstitial.adFailedListenerRemove();
HMSInterstitial.adLeaveListenerAdd(() => {
toast('HMSInterstitial adLeave');
});
// HMSInterstitial.adLeaveListenerRemove();
HMSInterstitial.adOpenedListenerAdd(() => {
toast('HMSInterstitial adOpened');
});
// HMSInterstitial.adOpenedListenerRemove();
HMSInterstitial.adLoadedListenerAdd((result) => {
toast('HMSInterstitial adLoaded');
console.log('HMSInterstitial adLoaded, result: ', result);
});
// HMSInterstitial.adLoadedListenerRemove();
HMSInterstitial.adClickedListenerAdd(() => {
toast('HMSInterstitial adClicked');
});
// HMSInterstitial.adClickedListenerRemove();
HMSInterstitial.adImpressionListenerAdd(() => {
toast('HMSInterstitial adImpression');
});
// HMSInterstitial.adImpressionListenerRemove();
return HMSInterstitial.allListenersRemove;
Testing
Run the below command to build the project
Code:
React-native run-android
Upon successful build, run the below command in the android directory of the project to create the signed apk.
Code:
gradlew assembleRelease
Results
Conclusion
Adding Interstitial ads seem very easy. Stay tuned for more ads activity.
Related
More information like this, you can visit HUAWEI Developer Forum
HMS Location Kit Flutter
Hi everyone , Today I try describing how we can use HMS Location kit Flutter Plugin also I prepare a demo project .
--You can see that at the end of page with Github link.
What is the Location Kit?
HUAWEI Location Kit assists developers in enabling their apps to get quick and accurate user locations and expand global positioning capabilities by using GPS, Wi-Fi, and base station locations.
Fused location: Provides a set of simple and easy-to-use APIs for you to quickly obtain the device location based on the GPS, Wi-Fi, and base station location data.
Activity identification: Identifies user motion status through the acceleration sensor, cellular network information, and magnetometer, helping you adjust your app based on user behavior.
Geofence: Allows you to set an interested area through an API so that your app can receive a notification when a specified action (such as leaving, entering, or lingering in the area) occurs.
If you want to more information about Location kit:
Location Kit
HUAWEI Location Kit combines GPS, Wi-Fi, and base station location data to allow you to quickly obtain precise user…developer.huawei.com
Location Flutter Plugin
The Flutter Location Plugin provides adaption code used for the HUAWEI Location Kit to use in Flutter platform. HUAWEI Location Kit combines the GPS, Wi-Fi, and base station locations to help you quickly obtain precise user locations, build up global positioning capabilities, and reach a wide range of users around the globe.
Configuring Your Flutter Project
Registering as a Developer
Before you get started, you must register as a HUAWEI developer and complete identity verification on the HUAWEI Developers website. For details, please refer to Registration and Verification.
Creating AppGalery Connect Project
Sign in to AppGallery Connect and click My apps.
Click the desired app name.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
3. Click the Develop tab.
4. In the App information area, click agconnect-services.json to download the configuration file.
If you have made any changes, such as setting the data storage location and enabling or managing APIs, you need to download the latest agconnect-services.json file and use it to replace the existing file in the app directory.
5. Create a Flutter project if you have not created one.
6. Run the following command and make sure that no errors are reported.
[project_path]> flutter doctor
7. Copy the agconnect-services.json file to the android/app directory of your Flutter project.
8. Copy the generated signature file to the android/app directory of your Flutter project.
9. Verify that the agconnect-services.json file and signature file are successfully added to the android/app directory of your Flutter project.
10. Open the build.gradle file in the android directory of your Flutter project.
a. Go to buildscript, and configure the Maven repository address and AppGallery Connect plugin for the HMS Core SDK.
Code:
buildscript {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
/*
* <Other dependencies>
*/
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
}
}
b. Go to allprojects, and configure the Maven repository address for the HMS Core SDK.
Code:
allprojects {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
}
11. Open the build.gradle file in the android/app directory of your Flutter project.
a. Add build dependencies.
Code:
dependencies {
implementation 'com.huawei.hms:location:4.0.3.301'
/*
* <Other dependencies>
*/
}
b. Add the apply plugin: ‘com.huawei.agconnect’ line after the apply plugin: ‘com.android.application’ line.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
c. Set minSdkVersion to 19 or higher in android > defaultConfig.
Code:
defaultConfig {
applicationId "<package_name>"
minSdkVersion 19
/*
* <Other configurations>
*/
}
The value of applicationId must match with that of package_name in the agconnect-services.json file.
d. Configure the signature in android based on the signature file information.
Code:
android {
/*
* <Other configurations>
*/
signingConfigs {
release {
storeFile file('<keystore_file>')
storePassword '<keystore_password>'
keyAlias '<key_alias>'
keyPassword '<key_password>'
}
}
buildTypes {
debug {
signingConfig signingConfigs.release
}
release {
signingConfig signingConfigs.release
}
}
}
Replace <keystore_file>, <keystore_password>, <key_alias> and <key_password> with matching entries in your signature file. For details about the app signing procedure in Flutter, please refer to App Signing in Flutter.
Integrating the Plugin
There are two ways to integrate the plugin to your project. Download the Location Kit Flutter Plugin and Using pub.dev HMS location_plugin
Download the Location Kit Flutter Plugin
Download the Location Kit Flutter Plugin and decompress it.
Open the pubspec.yaml file in your Flutter project and add the plugin dependency to the dependencies section.
Code:
dependencies:
huawei_location:
path: {library path}
Replace {library path} with the actual library path of the HUAWEI Location Kit Flutter plugin. For details, please refer to Using Packages.
3. Run following command to update the package information:
Code:
[project_path]> flutter pub get
4. Run the following command or click the run icon on the toolbar to start the app:
Code:
[project_path]> flutter run
Using pub.dev HMS location_plugin
Add this to your package’s pubspec.yaml file:
Code:
dependencies:
huawei_location: ^4.0.4+300
You can install packages from the command line:
with Flutter:
Code:
$ flutter pub get
Code:
Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.
Permissions
First of all we need permissions to access location and physical activity data.
Add location permission to manifest file.Define this permissions in android/app/src/main/AndroidManifest.xml as follows:
Create a PermissionHandle intance.
Code:
PermissionHandler permissionHandler;
Add initState() for initialize.
Code:
permissionHandler = PermissionHandler();
What does the service provide?
Check Permissions
Request Permissions
Code:
void requestPermission() async {
try {
bool status = await permissionHandler.requestLocationPermission();
setState(() {
infoText = "Is permission granted $status";
});
} catch (e) {
setState(() {
infoText = e.toString();
});
}
}
Fused Location
Create a FusedLocationProviderClient instance using the init() method and use the instance to call location-related APIs.
Code:
FusedLocationProviderClient locationService;
Add initState() for initialize.
Code:
locationService = FusedLocationProviderClient();
What does the service provide?
Last Location
Last Location With Address
Mock Location
Location Updates
Reference: Fused Location developer.huawei.com
To use mock location
To use the mock location function, go to Settings > System & updates > Developer options > Select mock location app and select the app for using the mock location function.
(If Developer options is unavailable, go to Settings > About phone and tap Build number for seven consecutive times. Then, Developer options will be displayed on System & updates.)
To use mock location feature first configure the mock location permission in the android/app/src/main/AndroidManifest.xml file.
Code:
<uses-permission
android:name="android.permission.ACCESS_MOCK_LOCATION"
tools:ignore="MockLocation,ProtectedPermissions" />
Listen Location Update Event
Call the method onLocationData that listens the location update events.
StreamSubscription<Location> streamSubs;
Add initState()
Code:
streamSubs = locationService.onLocationData.listen((location) {
print(location.toString());
});
Example method : getLastLocation()
Code:
void getLastLocation() async {
setState(() {
infoText = "";
});
try {
Location location = await locationService.getLastLocation();
setState(() {
infoText = location.toString();
});
} catch (e) {
setState(() {
infoText = e.toString();
});
}
}
Activity Identification
Creating an Activity Identification Service Client
ActivityIdentificationService locationService;
Add initState() for initialize.
locationService = FusedLocationProviderClient();
What does the service provide?
Activity Conversion Updates
Activity Conversion Request
Activity Identification Updates
Activity Identification Request
Listen Activity Identification Event
You can use the onActivityIdentification method to listen to and receive data from activity identification events.
Add initState() for initialize.
ActivityIdentificationService activityIdentificationService =
ActivityIdentificationService();
Code:
void onActivityIdentificationResponse(ActivityIdentificationResponse response) {
for (ActivityIdentificationData data
in response.activityIdentificationDatas) {
setChange(data.identificationActivity , data.possibility);
//data.identificationActivity include activity type like vehicle,bike etc.
//data.posibility The confidence for the user to execute the activity.
//The confidence ranges from 0 to 100. A larger value indicates more reliable activity authenticity.
}
}
void streamListen() {
streamSubscription =
activityIdentificationService.onActivityIdentification.listen(onActivityIdentificationResponse);
}
For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201314069177450189&fid=0101187876626530001
Introduction
In this article, we will be integration Text Search i.e. Keyword search feature of Site Kit. Huawei Site Kit provides core capabilities to developer to quickly build apps with which users can explore world around them seamlessly. Huawei Site kit provides following capabilities to developer as shown below.
Keyword search: returns the place list based on the keywords entered by user.
Nearby place search: Searches for nearby location based on current location of the user’s device.
Place detail search: Search for details about the place.
Place search suggestion: Returns list of suggested places.
Autocomplete: Returns an autocomplete place and a list of suggested places based on the entered keyword.
Development Overview
You need to install Flutter and Dart plugin in IDE and I assume that you have prior knowledge about the Flutter and Dart.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later.
Android studio software or Visual Studio or Code installed.
HMS Core (APK) 4.X or later.
Integration process
Step 1. Create flutter project
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Step 2. Add the App level gradle dependencies.
Choose inside project Android > app > build.gradle.
Java:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Add root level gradle dependencies
Java:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: Add the below permissions in Android Manifest file.
XML:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARES_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Step 4: Add Site Kit Plugin path in pubspec.yaml file under dependencies.
Step 5: Create a project in AppGallery Connect.
https://developer.huawei.com/consumer/en/codelab/HMSPreparation/index.html#0
pubspec.yaml
YAML:
name: sample_one
description: A new Flutter application.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
huawei_map:
path: ../huawei_map/
huawei_location:
path: ../huawei_location/
huawei_safetydetect:
path: ../huawei_safetydetect
huawei_site:
path: ../huawei_site
http: ^0.12.2
rflutter_alert: ^2.0.2
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
# add this line to your dependencies
toast: ^0.1.5
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
Declare and instantiate service object
YAML:
Future<void> initSearchService() async {
searchService = await SearchService.create(Uri.encodeComponent(API_KEY));
}
Create TextSearchRequest and its body
YAML:
Future<void> valueChanged(String value) async {
try {
TextSearchRequest request = new TextSearchRequest();
request.query = value;
request.location = Coordinate(lat: 12.9098, lng: 77.7440);
request.language = "en";
request.countryCode = "IN";
request.pageIndex = 1;
request.pageSize = 2;
request.radius = 5000;
TextSearchResponse response11 = await searchService.textSearch(request);
Map<String, dynamic> data = json.decode(response11.toJson());
print('-----------------------------------------------');
int i = 0;
for (String key in data.keys) {
if (key == 'sites') {
setState(() {
searchResponse = data['sites'][i]['name'].toString() +
'\n' +
data['sites'][i]['formatAddress'].toString() +
'\n' +
data['sites'][i]['address']['tertiaryAdminArea'].toString() +
'\n' +
data['sites'][i]['location']['lat'].toString() +
'\n' +
data['sites'][i]['location']['lng'].toString();
});
location = new LatLng(data['sites'][i]['location']['lat'],
data['sites'][i]['location']['lng']);
print(data[key]);
}
}
print('-----------------------------------------------');
} on PlatformException catch (e) {
setState(() {
searchResponse = e.toString();
});
}
}
Previous article on delivery app in flutter
Intermediate: Integration of Huawei map kit and Location kit in DeliveryApp in Flutter (Cross platform)Result
Tricks and Tips
Make sure you have downloaded latest plugin.
Make sure that updated plugin path in yaml.
Make sure that plugin unzipped in parent directory of project.
Makes sure that agconnect-services.json file added.
Make sure dependencies are added build file.
Run flutter pug get after adding dependencies.
Generating SHA-256 certificate fingerprint in android studio and configure in Ag-connect.
Conclusion
We have learnt how to integrate Huawei Site kit Text Search feature in delivery app in flutter. Where user can search for specific hotel in the search box and clicks on the result to see the list of orders. Similar way you can use Huawei Site kit as per user requirement in your application. In this part-1 I have covered Text Search that is Keyword Search you can expect more features implementation in part-2.
Thank you so much for reading, I hope this article helps you to understand the Huawei Site kit features in flutter.
Reference
Site Kit
Site Kit Plugin
Introduction
In this article, we will be integrating other Search features of Site kit, you can find previous article here, and Huawei Site Kit provides core capabilities to developer to quickly build apps with which users can explore world around them seamlessly. Huawei Site kit provides following Search capabilities to developer as shown below.
Keyword search: returns the place list based on the keywords entered by user.
Nearby place search: Searches for nearby location based on current location of the user’s device.
Place detail search: Search for details about the place.
Place search suggestion: Returns list of suggested places.
Autocomplete: Returns an autocomplete place and a list of suggested places based on the entered keyword.
Development Overview
You need to install Flutter and Dart plugin in IDE and I assume that you have prior knowledge about the Flutter and Dart.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later.
Android studio software or Visual Studio or Code installed.
HMS Core (APK) 4.X or later.
Integration process
Step 1. Create flutter project
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Step 2. Add the App level gradle dependencies, choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Add root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: Add the below permissions in Android Manifest file.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARES_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Step 4: Add plugin path in pubspec.yaml file under dependencies.
Step 5: Create a project in AppGallery Connect, find here.
pubspec.yaml
Code:
name: sample_one
description: A new Flutter application.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
huawei_map:
path: ../huawei_map/
huawei_location:
path: ../huawei_location/
huawei_safetydetect:
path: ../huawei_safetydetect
huawei_site:
path: ../huawei_site
http: ^0.12.2
rflutter_alert: ^2.0.2
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
# add this line to your dependencies
toast: ^0.1.5
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
Declare and instantiate service object
Code:
Future<void> initmySearchService() async {
searchService = await SearchService.create(Uri.encodeComponent(API_KEY));
}<strong> </strong>
How to I call QueryAutoCompleteRequest api ?
Code:
void autocomplete(String value) async {
// Declare an SearchService object and instantiate it. which i done in above initSearchService()
// Create QueryAutocompleteRequest and its body.
QueryAutocompleteRequest request = QueryAutocompleteRequest(query: value);
// Create QueryAutocompleteResponse object.
// Call queryAutocomplete() method.
// Assign the results.
QueryAutocompleteResponse response =
await searchService.queryAutocomplete(request);
if (response != null) {
Map<String, dynamic> data = json.decode(response.toJson());
List<dynamic> data2;
locations.clear();
entries.clear();
for (String key in data.keys) {
if (key == 'sites') {
data2 = data[key];
for (var element in data2) {
setState(() {
entries.add(element['name'] + "\n" + element['formatAddress']);
locations.add(new LatLng(
element['location']['lat'], element['location']['lng']));
});
}
}
}
}
}
How to I call QuerySuggestionRequest api ?
Code:
void querySuggestionSearch(String value) async {
// Declare an SearchService object and instantiate it. which i done in above initSearchService()
QuerySuggestionRequest request = QuerySuggestionRequest();
request.query = value;
request.location = Coordinate(lat: 12.893478, lng: 77.334595);
request.language = "en";
request.countryCode = "IN";
request.radius = 5000;
// Create QuerySuggestionResponse object.
// Call querySuggestion() method.
// Assign the results.
QuerySuggestionResponse response =
await searchService.querySuggestion(request);
if (response != null) {
Map<String, dynamic> data = json.decode(response.toJson());
List<dynamic> data2;
entries.clear();
for (String key in data.keys) {
if (key == 'sites') {
data2 = data[key];
for (var element in data2) {
setState(() {
entries.add(element['name'] + "\n" + element['formatAddress']);
locations.add(new LatLng(
element['location']['lat'], element['location']['lng']));
});
}
}
}
}
}
How to I call DetailSearchRequest api ?
Code:
void placeDetailSearch(String siteId) async {
// Declare an SearchService object and instantiate it. which i done in above initSearchService()
DetailSearchRequest request = DetailSearchRequest();
request.siteId = siteId;
request.language = "en";
// Create DetailSearchResponse object.
// Call detailSearch() method.
// Assign the results.
DetailSearchResponse response = await searchService.detailSearch(request);
if (response != null) {
Map<String, dynamic> data = json.decode(response.toJson());
List<dynamic> data2;
setState(() {
result = data['site'].toString();
});
} else {
print("Response is NULL");
}
}
Result
Note: Place detail search takes sit id as input and gives site information as result.
Tricks and Tips
Make sure that you have downloaded latest plugin.
Make sure that updated plugin path in yaml.
Make sure that plugin unzipped in parent directoryof project.
Makes sure that agconnect-services.json file added.
Make sure dependencies are added in build file.
Run flutter pug get after adding dependencies.
Generating SHA-256 certificate fingerprint in android studio and configure in Ag-connect.
Conclusion
In this article, we have learnt how to integrate Huawei Site kit Search capabilities for DeliveryApp in flutter. Where user can search for specific hotel or restaurants in the search box and clicks on the result to find the list of orders. Similar way you can use Huawei Site kit as per user requirement in your application.
Thank you so much for reading, I hope this article helps you to understand the Huawei Site kit Search capabilities in flutter.
Reference
Site kit
Site kit plugin
Original Source
Introduction
In this article, we will be learning how to integrate Huawei ML kit in Flutter application. Flutter ML plugin allows your apps to easily leverage Huawei’s long-term proven expertise in machine learning to support diverse artificial intelligence (AI) applications. ML plugin provides diversified leading machine learning capabilities that are easy to use, helping you develop various AI apps.
List of API’s ML plugin provides
Text-related services
Language-related services
Image-related services
Face/body-related services
Natural language processing
Custom model
In this article, we will be integrating some of the specific API’s related to Text-related services and Language-related service in flutter application.
Development Overview
You need to install Flutter and Dart plugin in IDE and I assume that you have prior knowledge about the Flutter and Dart.
Hardware Requirements
A computer (desktop or laptop) running Windows 10.
A Huawei phone (with the USB cable), which is used for debugging.
Software Requirements
Java JDK 1.7 or later.
Android studio software or Visual Studio or Code installed.
HMS Core (APK) 4.X or later.
Integration process
Step 1. Create flutter project.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Step 2. Add the App level gradle dependencies, choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
implementation 'com.huawei.agconnect:agconnect-core:1.3.1.300'
Add root level gradle dependencies.
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: Add the below permissions in Android Manifest file.
Code:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Step 4: Add plugin path in pubspec.yaml file under dependencies.
Step 5: Create a project in AppGallery Connect, find here.
pubspec.yaml
Code:
name: flutterdrivedemo123
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
huawei_account:
path: ../huawei_account
huawei_drive:
path: ../huawei_drive
huawei_ml:
path: ../huawei_ml
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
image_picker: ^0.8.0
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
Initialize MLApplication
Code:
MLApplication app = new MLApplication();
app.setApiKey(apiKey:"API_KEY");<strong> </strong>
Check required permissions
Code:
Future<void> checkPerms() async {
final bool isCameraPermissionGranted =
await MLPermissionClient().hasCameraPermission();
if (!isCameraPermissionGranted) {
final bool res = await MLPermissionClient()
.requestPermission([MLPermission.camera, MLPermission.storage]);
}
}
Select image and capture text from image
Code:
Future getImage() async {
final pickedFile = await picker.getImage(source: ImageSource.gallery);
//final pickedFile = await picker.getImage(source: ImageSource.camera);
setState(() {
if (pickedFile != null) {
File _image = File(pickedFile.path);
print('Path :' + pickedFile.path);
capturetext(pickedFile.path);
} else {
print('No image selected.');
}
});
}
Future<void> capturetext(String path) async {
// Create an MLTextAnalyzer object.
MLTextAnalyzer analyzer = new MLTextAnalyzer();
// Create an MLTextAnalyzerSetting object to configure the recognition.
MLTextAnalyzerSetting setting = new MLTextAnalyzerSetting();
// Set the image to be recognized and other desired options.
setting.path = path;
setting.isRemote = true;
setting.language = "en";
// Call asyncAnalyzeFrame to recognize text asynchronously.
MLText text = await analyzer.asyncAnalyzeFrame(setting);
print(text.stringValue);
setState(() {
msg = text.stringValue;
});
}
How to detect Language using ML kit?
Code:
Future<void> onClickDetect() async {
// Create an MLLangDetector object.
MLLangDetector detector = new MLLangDetector();
// Create MLLangDetectorSetting to configure detection.
MLLangDetectorSetting setting = new MLLangDetectorSetting();
// Set source text and detection mode.
setting.sourceText = text;
setting.isRemote = true;
// Get detection result with the highest confidence.
String result = await detector.firstBestDetect(setting: setting);
setState(() {
text = setting.sourceText + ": " + result;
});
}
How to translate Language using ML kit?
Code:
Future<void> onClickTranslate() async {
// Create an MLLocalTranslator object.
MLLocalTranslator translator = new MLLocalTranslator();
// Create an MLTranslateSetting object to configure translation.
MLTranslateSetting setting = new MLTranslateSetting();
// Set the languages for model download.
setting.sourceLangCode = "en";
setting.targetLangCode = "hi";
// Prepare the model and implement the translation.
final isPrepared = await translator.prepareModel(setting: setting);
if (isPrepared) {
// Asynchronous translation.
String result = await translator.asyncTranslate(sourceText: text);
setState(() {
text = result.toString();
});
}
// Stop translator after the translation ends.
bool result = await translator.stopTranslate();
}
Result
Tricks and Tips
Make sure that you have downloaded latest plugin.
Make sure that updated plugin path in yaml.
Make sure that plugin unzipped in parent directory of project.
Makes sure that agconnect-services.json file added.
Make sure dependencies are added in build file.
Run flutter pug get after adding dependencies.
Generating SHA-256 certificate fingerprint in android studio and configure in Ag-connect.
Conclusion
In this article, we have learnt how to integrate capabilities of Huawei ML kit in flutter application. Similar way you can use Huawei ML kit as per user requirement in your application.
Thank you so much for reading, I hope this article helps you to understand the Huawei ML kit capabilities in flutter.
Reference
MLkit
Plutter plugin
Original Source
useful sharing
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Introduction
In this article, we can learn how to integrate Huawei Ads Kit in an Application. I will be using Interstitial Ads. Interstitial ads are full-screen ads that cover the interface of an app. Such an ad is displayed when a user starts, pauses or exits an app, without disrupting the user's experience.
Ads Kit
Huawei Ads Kit leverages the vast user base of Huawei devices and Huawei's extensive data capabilities to provide you with the Publisher Service, helping you to monetize traffic.
HMS Ads Kit has 7 types of Ads kits. Now we can implement Interstitial Ads in this application.
Requirements
Any operating system (MacOS, Linux and Windows).
Must have a Huawei phone with HMS 4.0.2.300 or later.
Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Minimum API Level 21 is required.
Required EMUI 9.0.0 and later version devices.
Integrate HMS Dependencies
First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.
Create a project in android studio, refer Creating an Android Studio Project.
Generate a SHA-256 certificate fingerprint.
To generate SHA-256 certificate fingerprint. Choose View > Tool Windows > Gradle > Signingreport > SHA256 code.
Or use cmd as explained in SHA256 CODE
5. Create an App in AppGallery Connect.
6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory.
7. Enter SHA-256 certificate fingerprint and click Save.
8. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Code:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
9. Add the below plugin and dependencies in build.gradle(Module) file.
Code:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
Code:
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Ads Kit
Code:
Implementation 'com.huawei.hms:ads-lite:13.4.40.301'
10. Now Sync the gradle.
11. Add the required permission to the Manifestfile.xml file.
Code:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--check wifi state-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
12. If the project is using progaurd, copy and paste the below code in the progaurd-rules.pro file.
Code:
-keep class com.huawei.openalliance.ad.** { *; }
-keep class com.huawei.hms.ads.** { *; }
Development
In this example, we will place the interstitial ad between two activities. When the “CLICK TO START TRANSACTION” button is clicked on while in the MainActivity (the first activity in this example), an interstitial ad will be shown first, then the pin (the second activity in this example) will come to the place.
1. Create an interstitial ad object.
Code:
Create an InterstitialAd object and use the setAdId() method of the InterstitialAd class to set a test ad unit ID
private var interstitialAd: InterstitialAd? = null
var nextPageBtn: Button? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nextPageBtn = findViewById(R.id.btTrans)
interstitialAd = InterstitialAd(this)
interstitialAd.setAdId(adId)
interstitialAd.setAdListener(adListener)
}
2. Load an ad.
Code:
Call the loadAd() method of the InterstitialAd object to load an ad.
private fun loadInterstitialAd() {
...
// Load an interstitial ad.
val adParam = AdParam.Builder().build()
interstitialAd!!.loadAd(adParam)
...
}
3. Display an ad.
Code:
Call the isLoaded() method to check whether an ad has been loaded. If the ad has been loaded, call the show(Activity activity) method of the InterstitialAd object to display the ad.
private fun showInterstitial() {
// Display an interstitial ad.
if (interstitialAd != null && interstitialAd.isLoaded()) {
interstitialAd.show()
} else {
startActivity(Intent([email protected], pin::class.java))
}
}
4. Listen for ad events.
Code:
Call the setAdListener(AdListener adListener) method of the InterstitialAd class to add the ad event listener AdListener for the InterstitialAd object, and implement the methods in AdListener to listen to ad events.
fun adEvent() {
adListener = object : AdListener() {
fun onAdLoaded() {
// Called when an ad is loaded successfully.
super.onAdLoaded()
Toast.makeText([email protected], "Ad loaded", Toast.LENGTH_SHORT).show()
// Display an interstitial ad.
showInterstitial()
}
fun onAdFailed(errorCode: Int) {
// Called when an ad fails to be loaded.
Toast.makeText(
[email protected], "Ad load failed with error code: $errorCode",
Toast.LENGTH_SHORT
).show()
Log.d(
TAG,
"Ad load failed with error code: $errorCode"
)
startActivity(Intent([email protected], pin::class.java))
}
fun onAdClosed() {
// Called when an ad is closed
super.onAdClosed()
Log.d(TAG, "onAdClosed")
startActivity(Intent([email protected], pin::class.java))
}
fun onAdClicked() {
// Called when an ad is clicked.
Log.d(TAG, "onAdClicked")
super.onAdClicked()
adListener.onAdClosed()
}
fun onAdOpened() {
// Called when an ad is opened.
Log.d(TAG, "onAdOpened")
super.onAdOpened()
}
fun onAdLeave() {
// Called when an ad leaves an app.
...
}
fun onAdLeave() {
// Called when an ad leaves an app.
...
}
}
}
Activity_mail.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".MainActivity"
android:id="@+id/activity_main"
android:background="@color/purple_200">
<Button
android:id="@+id/btTrans"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/click_to_start_transaction"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="327dp" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome_to_world_s_best_bank"
android:textSize="20dp" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@drawable/hello" />
</RelativeLayout>
Adjust UI according to your application.
Result
Tips and Tricks
Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.
Make sure you have added the agconnect-services.json file to app folder.
Make sure you have added SHA-256 fingerprint without fail.
Make sure all the dependencies are added properly.
Conclusion
In this article, we have learnt integration of Ads Kit in application. It provides developers different capabilities to deliver good quality ads content to users.
Reference
Ads Kit: Documentation