Huawei AGC App Linking integration with Unity - Huawei Developers

More information like this, you can visit HUAWEI Developer Forumhttps://forums.developer.huawei.com...l/en/home?channelname=HuoDong59&ha_source=xda​
Introduction:
In this article, we will cover Integration of AGC App Linking in Unity Project using Official Plugin (Huawei HMS Core App Services).
Requirements:
1. Unity Editor
2. Huawei device
3. Visual Studio
Follows the steps.
Step 1. Create Unity Project.
Click unity icon.
Click NEW, select 3D, Project Name and Location.
Click CREATE, as follows.
{
"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. Click Asset Store, search Huawei HMS Core App Services and click Import, as follows.
Step 3. Once import is successful, verify directory in Assets > Huawei HMS Core App Services path, as follows.
Step 4. Click Console and create a New Project.
Step 5. Choose Project Settings > Player and edit the required options in Publishing Settings, as follows.
Step 6. Verify the files created in Step 5.
Step 7. Download agconnect-services.json and copy to Assets>Plugins>Android, as follows.
Step 8. Update the Package Name.
Step 9. Open LauncherTemplate.gradle and add below line
Code:
apply plugin: 'com.huawei.agconnect'
Step 10. Open "baseProjectTemplate.gradle" and add lines, as follows.
Code:
maven {url 'https://developer.huawei.com/repo/'}
Code:
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 11. Open "mainTemplate.gradle" and add lines like shown below
Code:
apply plugin: 'com.huawei.agconnect'
Code:
implementation 'com.huawei.agconnect:agconnect-core:1.4.1.300'
implementation 'com.huawei.agconnect:agconnect-applinking:1.4.0.300'
implementation 'com.huawei.hms:hianalytics:5.0.3.300'
Step 12. Open AndroidManifest file and Add Activity like shown below.
Code:
<activity android:name="com.hms.hms_analytic_activity.TestAppLinksActivity"
android:theme="@style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:host="developer.huawei.com" android:scheme="https" />
<data android:host="developer.huawei.com" android:scheme="http" />
</intent-filter>
</activity>
Step 13. Create TestAppLinksActivity.java, JavaCallBack.java and place it in Assets->Plugins->Android.
Code:
//package com.test.applinks;
package com.hms.hms_analytic_activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.unity3d.player.UnityPlayerActivity;
import android.widget.Toast;
import com.huawei.agconnect.applinking.AGConnectAppLinking;
import com.huawei.agconnect.applinking.AppLinking;
import com.huawei.agconnect.applinking.ShortAppLinking;
//import androidx.appcompat.app.AppCompatActivity;
import com.huawei.agconnect.applinking.AGConnectAppLinking;
public class TestAppLinksActivity extends UnityPlayerActivity {
public static JavaCallback callback;
private static String agcLink = null;
private static final String DOMAIN_URI_PREFIX = "https://testulink.dra.agconnect.link";
//private static final String DEEP_LINK = "rmOb2";
private static final String DEEP_LINK = "https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides?id=123";
private static String deepLinkData = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("TestAppLinksActivity", "TestAppLinksActivity onCreate>> @@");
mContext = this.getApplicationContext();
handleAppLinking(getIntent());
}
public static void setCallback(JavaCallback callback1) {
Log.e("TestAppLinksActivityl", "setCallback>> @@");
callback = callback1;
if(callback != null){
Log.e("TestAppLinksActivity", "update c # script >>>>");
callback.OnJavaCallback(deepLinkData);
}else{
Log.e("TestAppLinksActivity", "TestAppLinksActivity callback is null plz initialize >>>>");
}
}
private void handleAppLinking(Intent intent) {
AGConnectAppLinking.getInstance().getAppLinking(this, intent).addOnSuccessListener(resolvedLinkData -> {
Uri deepLink = null;
if (resolvedLinkData != null) {
deepLink = resolvedLinkData.getDeepLink();
Log.e("TestAppLinksActivity", " [email protected]!!!$$->"+deepLink.toString());
deepLinkData = deepLink.toString();
if(callback != null){
Log.e("TestAppLinksActivity", "update c # script");
callback.OnJavaCallback(deepLink.toString());
}else{
Log.e("TestAppLinksActivity", "callback is null plz initialize");
}
}
}).addOnFailureListener(e -> {
Log.e("TestAppLinksActivity", "getAppLinking:onFailure", e);
});
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleAppLinking(intent);
}
public static void createAppLinking() {
AppLinking.Builder builder = new AppLinking.Builder().setUriPrefix(DOMAIN_URI_PREFIX)
.setDeepLink(Uri.parse(DEEP_LINK));
//longTextView.setText(builder.buildAppLinking().getUri().toString());
Log.e("TestAppLinksActivity", "createAppLinking long -->"+builder.buildAppLinking().getUri().toString());
agcLink = builder.buildAppLinking().getUri().toString();
builder.buildShortAppLinking(ShortAppLinking.LENGTH.SHORT).addOnSuccessListener(shortAppLinking -> {
//shortTextView.setText(shortAppLinking.getShortUrl().toString());
Log.e("TestAppLinksActivity", "createAppLinking short -->"+shortAppLinking.getShortUrl().toString());
agcLink = shortAppLinking.getShortUrl().toString();
}).addOnFailureListener(e -> {
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("TestAppLinksActivity", "createAppLinking failure -->"+e.getMessage());
});
}
//public void shareLink() {
public static void shareLink(Activity activity){
if (agcLink != null) {
Log.e("TestAppLinksActivity", "shareLink agcLink is not null start activity");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, agcLink);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
//startActivity(intent);
}else{
Log.e("TestAppLinksActivity", " shareLink agcLink is null");
}
}
private static Context mContext;
public static Context getAppContext(){
return mContext;
}
}
code explanation : https://developer.huawei.com/consumer/en/codelab/AppLinking/index.html#7
Code:
package com.hms.hms_analytic_activity;
public interface JavaCallback {
void OnJavaCallback(String index);
}
Note : Java classes are using package name com.hms.hms_analytic_activity & we dont create any folder structure, this is allowed.
For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202361288668900258&fid=0101188387844930001

Related

Android App Bundle - Features on demand--Part 2

More articles like this, you can visit HUAWEI Developer Forum.​
In this article, we will build Android App Bundle (AAB).
In the previous article, we have learned about Huawei Dynamic Ability. Refer the URL:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201297090480680014&fid=0101187876626530001
If you have not read my previous article which is part 1 of this article. I would recommend you to kindly go through the link below:
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201297090480680014&fid=0101187876626530001
1. Dynamic Ability:
Dynamic Ability is a service in which HUAWEI AppGallery implements dynamic loading based on the Android App Bundle technology.
Apps integrated with the Dynamic Ability SDK can dynamically download features or language packages from HUAWEI AppGallery as required, reducing the unnecessary consumption of network traffic and device storage space.
2. Android App Bundle:
It is a new upload format that includes all your apps compiled code and resources, but accepts APK generation and signing to AppGallery. Traditionally, Android apps are distributed using a special file called an Android Package (.apk).
Let’s start development:
We have created following project directory:
{
"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"
}
Let’s see the gradle file:
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
android {
compileSdkVersion 28
buildToolsVersion "28.0.3"
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
dataBinding {
enabled = true
}
defaultConfig {
applicationId "com.hms.manoj.aab"
minSdkVersion 26
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
dynamicFeatures = [":repository", ":retrofit", ":viewmodel"]
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
// Android MVVM Components
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
// Android Support Library
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
//Huawei Dynamic ability
api 'com.huawei.hms:dynamicability:1.0.11.302'
}
Let’s see the manifest file:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.hms.manoj.aab">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name="com.hms.manoj.aab.MyApp"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="com.hms.manoj.aab.ui.ShowsActivity"
android:launchMode="singleTask"
android:theme="@style/AppTheme"
android:windowSoftInputMode="adjustNothing">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.hms.manoj.aab.ui.ShowDetailActivity"
android:screenOrientation="fullSensor"
android:label="@string/app_name" />
<activity
android:name="com.hms.manoj.aab.ui.CastActivity"
android:screenOrientation="fullSensor"
android:label="@string/app_name" />
</application>
</manifest>
Let’s see the implementation of feature installation inside the code:
Code:
package com.hms.manoj.aab.ui;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import com.hms.manoj.aab.R;
import com.hms.manoj.aab.apiconnector.response.Show;
import com.hms.manoj.aab.databinding.ActivityShowsBinding;
import com.hms.manoj.aab.ui.adapter.ShowAdapter;
import com.hms.manoj.aab.viewmodel.ShowsViewModel;
import com.huawei.hms.feature.install.FeatureInstallManager;
import com.huawei.hms.feature.install.FeatureInstallManagerFactory;
import com.huawei.hms.feature.listener.InstallStateListener;
import com.huawei.hms.feature.model.FeatureInstallException;
import com.huawei.hms.feature.model.FeatureInstallRequest;
import com.huawei.hms.feature.model.FeatureInstallSessionStatus;
import com.huawei.hms.feature.model.InstallState;
import com.huawei.hms.feature.tasks.FeatureTask;
import com.huawei.hms.feature.tasks.listener.OnFeatureCompleteListener;
import com.huawei.hms.feature.tasks.listener.OnFeatureFailureListener;
import com.huawei.hms.feature.tasks.listener.OnFeatureSuccessListener;
import java.util.List;
import static com.hms.manoj.aab.utils.Utils.KEY_SHOW_ID;
public class ShowsActivity extends AppCompatActivity {
public static final String TAG=ShowsActivity.class.getName();
private FeatureInstallManager mFeatureInstallManager;
private int sessionId = 10086;
private ActivityShowsBinding mBinding;
private ShowsViewModel mShowsViewModel;
private InstallStateListener mStateUpdateListener = new InstallStateListener() {
@Override
public void onStateUpdate(InstallState state) {
Log.d(TAG, "install session state " + state);
if (state.status() == FeatureInstallSessionStatus.REQUIRES_USER_CONFIRMATION) {
try {
mFeatureInstallManager.triggerUserConfirm(state, ShowsActivity.this, 1);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
return;
}
if (state.status() == FeatureInstallSessionStatus.REQUIRES_PERSON_AGREEMENT) {
try {
mFeatureInstallManager.triggerUserConfirm(state, ShowsActivity.this, 1);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
return;
}
if (state.status() == FeatureInstallSessionStatus.INSTALLED) {
Log.i(TAG, "installed success ,can use new feature");
return;
}
if (state.status() == FeatureInstallSessionStatus.UNKNOWN) {
Log.e(TAG, "installed in unknown status");
return;
}
if (state.status() == FeatureInstallSessionStatus.DOWNLOADING) {
long process = state.bytesDownloaded() * 100 / state.totalBytesToDownload();
Log.d(TAG, "downloading percentage: " + process);
return;
}
if (state.status() == FeatureInstallSessionStatus.FAILED) {
Log.e(TAG, "installed failed, errorcode : " + state.errorCode());
return;
}
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setTitle("All Shows");
mFeatureInstallManager = FeatureInstallManagerFactory.create(this);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_shows);
mShowsViewModel = ViewModelProviders.of(this).get(ShowsViewModel.class);
wait(true);
getShowList();
}
public void installFeature(View view) {
if (mFeatureInstallManager == null) {
return;
}
FeatureInstallRequest request = FeatureInstallRequest.newBuilder()
.addModule("repository")
.addModule("retrofit")
.addModule("viewmodel")
.build();
final FeatureTask<Integer> task = mFeatureInstallManager.installFeature(request);
task.addOnListener(new OnFeatureSuccessListener<Integer>() {
@Override
public void onSuccess(Integer integer) {
Log.d(TAG, "load feature onSuccess.session id:" + integer);
}
});
task.addOnListener(new OnFeatureFailureListener<Integer>() {
@Override
public void onFailure(Exception exception) {
if (exception instanceof FeatureInstallException) {
int errorCode = ((FeatureInstallException) exception).getErrorCode();
Log.d(TAG, "load feature onFailure.errorCode:" + errorCode);
} else {
exception.printStackTrace();
}
}
});
task.addOnListener(new OnFeatureCompleteListener<Integer>() {
@Override
public void onComplete(FeatureTask<Integer> featureTask) {
if (featureTask.isComplete()) {
Log.d(TAG, "complete to start install.");
if (featureTask.isSuccessful()) {
Integer result = featureTask.getResult();
sessionId = result;
Log.d(TAG, "succeed to start install. session id :" + result);
} else {
Log.d(TAG, "fail to start install.");
Exception exception = featureTask.getException();
exception.printStackTrace();
}
}
}
});
Log.d(TAG, "start install func end");
}
private void wait(boolean isLoading) {
if (isLoading) {
mBinding.loaderLayout.rootLoader.setVisibility(View.VISIBLE);
mBinding.layout.shows.setVisibility(View.GONE);
} else {
mBinding.loaderLayout.rootLoader.setVisibility(View.GONE);
mBinding.layout.shows.setVisibility(View.VISIBLE);
}
}
private void getShowList() {
mShowsViewModel.getShowsLiveData().observeForever(showList -> {
if (showList != null) {
wait(false);
String eventName = "Show Success";
Bundle bundle = new Bundle();
bundle.putInt("Show Size", showList.size());
setDataIntoAdapter(showList);
} else {
wait(false);
}
});
}
private void setDataIntoAdapter(List<Show> list) {
mBinding.layout.shows.setLayoutManager(new GridLayoutManager(this, 2));
mBinding.layout.shows.setAdapter(new ShowAdapter(list, (item) -> {
Intent intent = new Intent(getBaseContext(), ShowDetailActivity.class);
intent.putExtra(KEY_SHOW_ID, String.valueOf(item.getId()));
String eventName = "Choosed Show";
Bundle bundle = new Bundle();
bundle.putInt("Show ID", item.getId());
startActivity(intent);
}));
}
@Override
protected void onResume() {
super.onResume();
if (mFeatureInstallManager != null) {
mFeatureInstallManager.registerInstallListener(mStateUpdateListener);
}
}
@Override
protected void onPause() {
super.onPause();
if (mFeatureInstallManager != null) {
mFeatureInstallManager.unregisterInstallListener(mStateUpdateListener);
}
}
}
We will create 3 Dynamic Feature module under android project.
1. Repository Module
2. Network Module
3. ViewModel Module
Let’s create Repository Module:
In this module, we have created ShowRepository class which communicate between network and UI components.
Let’s see gradle file:
Code:
apply plugin: 'com.android.dynamic-feature'
android {
compileSdkVersion 29
defaultConfig {
minSdkVersion 27
targetSdkVersion 29
versionCode 1
versionName "1.0"
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project(':app')
// RxAndroid
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
}
Note: Module should have this in the first line, as it is a dynamic feature:
Code:
apply plugin: 'com.android.dynamic-feature'
Let’s see manifest file of this module:
Code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.hms.android.repository">
<dist:module
dist:instant="false"
dist:title="@string/title_repository">
<dist:delivery>
<dist:on-demand />
</dist:delivery>
<dist:fusing dist:include="true" />
</dist:module>
</manifest>
Let’s create Network Module:
In this module, we have implemented all business model.
Let’s see gradle file:
Code:
apply plugin: 'com.android.dynamic-feature'
android {
compileSdkVersion 29
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
defaultConfig {
minSdkVersion 27
targetSdkVersion 29
versionCode 1
versionName "1.0"
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation project(':app')
// RxAndroid
implementation 'io.reactivex.rxjava2:rxjava:2.2.8'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
// Android MVVM Components
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0'
}
Let’s see manifest file of this module:
Code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.hms.android.viewmodel">
<dist:module
dist:instant="false"
dist:title="@string/title_viewmodel">
<dist:delivery>
<dist:on-demand />
</dist:delivery>
<dist:fusing dist:include="true" />
</dist:module>
</manifest>
Let’s build Android App Bundle:
We need to follow the following steps to generate .aab file.
Follow the steps to generate aab file.
1. Step: Goto->Build->Build Bundle(s)/APK(s)->Build Bundle(s). Choose Build > Build Bundle(s)/APK(s) > Build Bundle(s)
2. After build success, following dialog-box displayed.
3. Click locate text and the output folder will be displayed.
Note: Singing the aab file carefully and upload on AppGallery portal.
4. Provide your project/app information in AppGallery portal:
5. Upload your aab/apk file in draft section.
Now We can download the application from app gallery(After approval).
Time being, we can run that apk in our mobile device.
Let's see the result.
If you have any doubts or queries. Leave your valuable comment below.

Location Kit Integration in Unity - Official Plugin (Huawei HMS Core App Services)

More information like this, you can visit HUAWEI Developer Forum​
Original link: https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201350575696000176&fid=0101187876626530001
Introduction:
In this article, we will cover Integration of Location Kit in Unity Project using Official Plugin (Huawei HMS Core App Services).
{
"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"
}
Requirements:
1. Unity Editor
2. Huawei device
3. Visual Studio
Output:
Fetch and show the users current location (Latitude and Longitude) using Huawei Location Kit.
Follows the steps.
1. Create Unity Project.
Click unity icon.
Click NEW, select 3D, Project Name and Location.
Click CREATE, as follows.
2. Click Asset Store, search Huawei HMS Core App Services and click Import, as follows.
3. Once import is successful, verify directory in Assets > Huawei HMS Core App Services path, as follows.
4. Click Console and create a New Project.
5. Choose Project Settings > Player and edit the required options in Publishing Settings, as follows.
6. Verify the files created in Step 5.
7. Download agconnect-services.json and copy to Assets/Plugins/Android, as follows.
8. Update the Package Name.
9. Open LauncherTemplate.gradle and add below line
Code:
implementation 'com.android.support:appcompat-v7:28.0.0'
10. Open AndroidManifest file & Add below permissions.
Code:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
11. Add Receiver Like shown below in Android Manifest File.
Code:
<receiver
android:name="com.unity.hms.location.LocationBroadcastReceiver"
android:exported="true">
</receiver>
12. Open "baseProjectTemplate.gradle" and add lines, as follows.
Code:
maven {url 'https://developer.huawei.com/repo/'}
13. Open "mainTemplate.gradle" and add lines like shown below
Code:
implementation 'com.huawei.hms:location:5.0.0.301'
implementation 'com.huawei.hms:ads-lite:13.4.30.301'
14. Scripting, create two classes.
TestClass.cs
Code:
using System.Collections;
using System.Collections.Generic;
using HuaweiHms;
using UnityEngine;
public class TestClass : IBroadcastReceiver
{
override
public void onReceive(Context arg0, Intent arg1)
{
Debug.LogError("kamal onReceive--->");
}
}
RegisterReceiver.cs
Code:
using System.Collections;
using System.Collections.Generic;
using HuaweiHms;
using UnityEngine;
using UnityEngine.UI;
public class RegisterReceiver : MonoBehaviour
{
static FusedLocationProviderClient fusedLocationProviderClient;
static LocationRequest locatinoRequest;
public Text latitude;
public Text longitude;
private void Awake()
{
//AdListener add = new AdListener();
TestClass receiver = new TestClass();
BroadcastRegister.CreateLocationReceiver(receiver);
Debug.LogError("kamal RegisterReceiver--->");
//LocationRequest request = new LocationRequest();
//request.setInterval(10000);
//request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locatinoRequest = LocationRequest.create();
locatinoRequest.setInterval(10000);
locatinoRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(locatinoRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
Activity act = new Activity();
//Context context = new Context();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(act);
SettingsClient settingsClient = LocationServices.getSettingsClient(act);
settingsClient.checkLocationSettings(locationSettingsRequest)
.addOnSuccessListener(new OnSuccessListenerTemp(this))
.addOnFailureListener(new OnFailureListenerTemp());
Debug.LogError("kamal RegisterReceiver request send--->");
}
class OnSuccessListenerTemp : OnSuccessListener
{
private RegisterReceiver registerReceiver;
public OnSuccessListenerTemp(RegisterReceiver registerReceiver)
{
this.registerReceiver = registerReceiver;
}
public override void onSuccess(AndroidJavaObject arg0) {
Debug.LogError("kamal onSuccess 0--->");
fusedLocationProviderClient.requestLocationUpdates(locatinoRequest, new OnLocationCallback(this.registerReceiver), Looper.getMainLooper())
.addOnSuccessListener(new OnReqSuccessListenerTemp())
.addOnFailureListener(new OnReqFailureListenerTemp())
;
}
};
class OnReqSuccessListenerTemp : OnSuccessListener
{
public override void onSuccess(AndroidJavaObject arg0)
{
Debug.LogError("kamal onSuccess 1--->");
}
};
class OnReqFailureListenerTemp : OnFailureListener
{
public override void onFailure(Exception arg0)
{
Debug.LogError("kamal onFailure 2--->");
}
}
class OnLocationCallback : LocationCallback {
private RegisterReceiver registerReceiver;
public OnLocationCallback(RegisterReceiver registerReceiver)
{
this.registerReceiver = registerReceiver;
}
public override void onLocationAvailability(LocationAvailability arg0) {
Debug.LogError("kamal onLocationAvailability 0--->");
}
public override void onLocationResult(LocationResult locationResult) {
Location location = locationResult.getLastLocation();
HWLocation hWLocation = locationResult.getLastHWLocation();
Debug.LogError("kamal onLocationResult found location--->");
if (location != null) {
Debug.LogError("kamal getLatitude--->" + location.getLatitude() + "<-getLongitude->" + location.getLongitude());
//latitude.text = "Latitude-->" + location.getLatitude();
//longitude.text = "Longitude-->" + location.getLongitude() ;
//RegisterReceiver.this.updateData(location);
registerReceiver.updateData(location);
}
if (hWLocation != null)
{
string country = hWLocation.getCountryName();
string city = hWLocation.getCity();
string countryCode = hWLocation.getCountryCode();
string dd = hWLocation.getPostalCode();
Debug.LogError("kamal country--->"+country + "<-city->"+city+ "<-countrycode->"+countryCode+"<-postal code->"+dd);
}
else {
Debug.LogError("kamal onLocationResult found location hWLocation is null--->");
}
}
}
private void updateData(Location location) {
latitude.text = "Latitude-->" + location.getLatitude();
longitude.text = "Longitude-->" + location.getLongitude() ;
}
class OnFailureListenerTemp : OnFailureListener {
public override void onFailure(Exception arg0) {
Debug.LogError("kamal onFailure--->");
}
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
15. Code explanation, follow below URL.
https://developer.huawei.com/consumer/en/codelab/HMSLocationKit/index.html#5
16. Run Attach Script to Scene, create two Text Views and assign them to script for showing latitude and longitude.
17. Run the project and enable location permission manually, as its demo I did not do it programmatically.
Conclusion
Latitude and Longitude both are coming on game screen, as shown below
References
Integrate Unity & Account Kit
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202334275608690050&fid=0101187876626530001
Integrate Unity & In App purchase
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201335993101470045&fid=0101187876626530001
HMS Ads integration with Unity
https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201337158850280060&fid=0101187876626530001

Huawei Remote Configuration integration with Unity

More information like this, you can visit HUAWEI Developer Forum​
Introduction:
In this article, we will cover Integration of Remote Configuration in Unity Project using Official Plugin (Huawei HMS Core App Services).
Requirements:
1. Unity Editor
2. Huawei device
3. Visual Studio
Follows the steps:
Step 1. Create Unity Project.
Click unity icon.
Click NEW, select 3D, Project Name and Location.
Click CREATE, as follows.
{
"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. Click Asset Store, search Huawei HMS Core App Services and click Import, as follows.
Step 3. Once import is successful, verify directory in Assets > Huawei HMS Core App Services path, as follows.
Step 4. Click Console and create a New Project.
Step 5. Choose Project Settings > Player and edit the required options in Publishing Settings, as follows.
Step 6. Verify the files created in Step 5.
Step 7. Download agconnect-services.json and copy to Assets>Plugins>Android, as follows.
Step 8. Update the Package Name.
Step 9. Open LauncherTemplate.gradle and add below line
Code:
apply plugin: 'com.huawei.agconnect'
Step 10. Open "baseProjectTemplate.gradle" and add lines, as follows.
Code:
maven {url 'https://developer.huawei.com/repo/'}
Code:
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 11. Open "mainTemplate.gradle" and add lines like shown below
Code:
apply plugin: 'com.huawei.agconnect'
Code:
implementation 'com.huawei.agconnect:agconnect-core:1.3.1.300'
implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.4.1.300'
Step 12. Open AndroidManifest file and Add Activity like shown below.
Code:
<activity android:name="com.hms.hms_analytic_activity.TestAppLinksActivity"
android:theme="@style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
</activity>
Step 13. Create TestAppLinksActivity.java and place it in Assets->Plugins->Android.
TestAppLinksActivity.java
Code:
//package com.test.applinks;
package com.hms.hms_analytic_activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.unity3d.player.UnityPlayerActivity;
import android.widget.Toast;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.huawei.agconnect.remoteconfig.AGConnectConfig;
import com.huawei.agconnect.remoteconfig.ConfigValues;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.unity3d.player.R;
//import com.test.remote.config.R;
import com.test.mylibrary.MyLibClass;
import com.test.mylibrary.MyContext;
//import androidx.appcompat.app.AppCompatActivity;
public class TestAppLinksActivity extends UnityPlayerActivity {
private static final String GREETING_KEY = "GREETING_KEY";
private static final String SET_BOLD_KEY = "SET_BOLD_KEY";
private static AGConnectConfig config;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("TestAppLinksActivity ", "onCreate>> @@");
config = AGConnectConfig.getInstance();
MyLibClass a = new MyLibClass(new MyContext(this));
//config.applyDefault(R.xml.remote_config);
config.applyDefault(a.getRemoteConfigFileId());
String key = config.getValueAsString(GREETING_KEY);
Boolean isBold = config.getValueAsBoolean(SET_BOLD_KEY);
Log.e("TestAppLinksActivity ", " values from remote config files-key->>"+key+"<-----isBold---->"+isBold);
}
public static void getSavedConfig() {
Log.e("TestAppLinksActivity ", " getSavedConfig >>");
config = AGConnectConfig.getInstance();
String key = config.getValueAsString(GREETING_KEY);
Boolean isBold = config.getValueAsBoolean(SET_BOLD_KEY);
Log.e("TestAppLinksActivity ", "values from saved remote config -key->>"+key+"<-----isBold---->"+isBold);
}
public static void setCallback() {
Log.e("TestAppLinksActivity ", "setCallback>> @@");
fetchAndApply();
}
private static void fetchAndApply(){
config = AGConnectConfig.getInstance();
Log.e("TestAppLinksActivity", "fetchAndApply config>>"+config);
String key = config.getValueAsString(GREETING_KEY);
Boolean isBold = config.getValueAsBoolean(SET_BOLD_KEY);
Log.e("TestAppLinksActivity", "values from remote config files-key->>"+key+"<-----isBold---->"+isBold);
Log.e("TestAppLinksActivity", "fetchAndApply>>");
config.fetch(0).addOnSuccessListener(new OnSuccessListener<ConfigValues>() {
@Override
public void onSuccess(ConfigValues configValues) {
Log.e("TestAppLinksActivity", "fetchAndApply onSuccess>>"+configValues);
// Apply Network Config to Current Config
config.apply(configValues);
//updateUI();
String key = config.getValueAsString(GREETING_KEY);
Boolean isBold = config.getValueAsBoolean(SET_BOLD_KEY);
Log.e("TestAppLinksActivity", "values from updated remote config files-key->>"+key+"<-----isBold---->"+isBold);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
//textView.setText("fetch setting failed: " + e.getMessage());
Log.e("TestAppLinksActivity", " fetchAndApply onFailure>>"+e.getMessage());
}
});
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
//handleAppLinking(intent);
}
}
Code Explanation - Please refer
https://developer.huawei.com/consumer/en/codelab/RemoteConfig/index.html#8
For full content, you can visit https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0201361479871390297&fid=0101188387844930001

Validate your news: Feat. Huawei ML Kit (Text Image Super-Resolution)

Introduction
Quality improvement has become crucial in this era of digitalization where all our documents are kept in the folders, shared over the network and read on the digital device.
Imaging the grapple of an elderly person who has no way to read and understand an old prescribed medical document which has gone blurred and deteriorated.
Can we evade such issues??
{
"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"
}
Let’s unbind what Huawei ML Kit offers to overcome such challenges of our day to day life.
Huawei ML Kit provides Text Image Super-Resolution API to improvise the quality and visibility of old and blurred text on an image.
Text Image Super-Resolution can zoom in an image that contains the text and significantly improve the definition of the text.
Limitations
The text image super-resolution service requires images with the maximum resolution 800 x 800 px and the length greater than or equal to 64 px.
Development Overview
Prerequisite
Must have a Huawei Developer Account
Must have Android Studio 3.0 or later
Must have a Huawei phone with HMS Core 4.0.2.300 or later
EMUI 3.0 or later
Software Requirements
Java SDK 1.7 or later
Android 5.0 or later
Preparation
Create an app or project in the Huawei app gallery connect.
Provide the SHA Key and App Package name of the project in App Information Section and enable the ML Kit API.
Download the agconnect-services.json file.
Create an Android project.
Integration
Add below to build.gradle (project)file, under buildscript/repositories and allprojects/repositories.
Code:
Maven {url 'http://developer.huawei.com/repo/'}
Add below to build.gradle (app) file, under dependencies.
To use the Base SDK of ML Kit-Text Image Super Resolution, add the following dependencies:
Code:
dependencies{
// Import the base SDK.
implementation 'com.huawei.hms:ml-computer-vision-textimagesuperresolution:2.0.3.300'
}
Adding permissions
Code:
<uses-permission android:name="android.permission.CAMERA " />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Automatically Updating the Machine Learning Model
Add the following statements to the AndroidManifest.xml file to automatically install the machine learning model on the user’s device.
Code:
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value= "tisr"/>
Development Process
This article focuses on demonstrating the capabilities of Huawei’s ML Kit: Text Image Super- Resolution API’s.
Here is the example which explains how can we integrate this powerful API to leverage the benefits of improvising the Text-Image quality and provide full accessibility to the reader to read the old and blur newspapers from an online news directory.
TextImageView Activity : Launcher Activity
This is main activity of “The News Express “application.
Code:
package com.mlkitimagetext.example;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.mlkitimagetext.example.textimagesuperresolution.TextImageSuperResolutionActivity;
public class TextImageView extends AppCompatActivity {
Button NewsExpress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_image_view);
NewsExpress = findViewById(R.id.bt1);
NewsExpress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(TextImageView.this, TextImageSuperResolutionActivity.class));
}
});
}
}
Activity_text_image_view.xml
This is the view class for the above activity class.
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/im3">
<LinearLayout
android:id="@+id/ll_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:orientation="vertical">
<Button
android:id="@+id/bt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent"
android:layout_gravity="center"
android:text="The News Express"
android:textAllCaps="false"
android:textStyle="bold"
android:textSize="34dp"
android:textColor="@color/mlkit_bcr_text_color_white"></Button>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textStyle="bold"
android:text="Validate Your News"
android:textSize="20sp"
android:layout_gravity="center"
android:textColor="#9fbfdf"/>
</LinearLayout>
</RelativeLayout>
TextImageSuperResolutionActivity
This activity class performs following actions:
Image picker implementation to pick the image from the gallery
Convert selected image to Bitmap
Create a text image super-resolution analyser.
Create an MLFrame object by using android.graphics.Bitmap.
Perform super-resolution processing on the image with text.
Stop the analyser to release detection resources.
Code:
package com.mlkitimagetext.example;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.mlsdk.common.MLException;
import com.huawei.hms.mlsdk.common.MLFrame;
import com.huawei.hms.mlsdk.textimagesuperresolution.MLTextImageSuperResolution;
import com.huawei.hms.mlsdk.textimagesuperresolution.MLTextImageSuperResolutionAnalyzer;
import com.huawei.hms.mlsdk.textimagesuperresolution.MLTextImageSuperResolutionAnalyzerFactory;
import com.mlkitimagetext.example.R;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
public class TextImageSuperResolutionActivity<button> extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "TextSuperResolutionActivity";
private MLTextImageSuperResolutionAnalyzer analyzer;
private static final int INDEX_3X = 1;
private static final int INDEX_ORIGINAL = 2;
private ImageView imageView;
private Bitmap srcBitmap;
Uri imageUri;
Boolean ImageSetupFlag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_super_resolution);
imageView = findViewById(R.id.image);
imageView.setOnClickListener(this);
findViewById(R.id.btn_load).setOnClickListener(this);
createAnalyzer();
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.btn_load) {
openGallery();
}else if (view.getId() == R.id.image)
{
if(ImageSetupFlag != true)
{
detectImage(INDEX_3X);
}else {
detectImage(INDEX_ORIGINAL);
ImageSetupFlag = false;
}
}
}
private void openGallery() {
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == 1){
imageUri = data.getData();
try {
srcBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
//BitmapFactory.decodeResource(getResources(), R.drawable.new1);
imageView.setImageURI(imageUri);
}
}
private void release() {
if (analyzer == null) {
return;
}
analyzer.stop();
}
private void detectImage(int type) {
if (type == INDEX_ORIGINAL) {
setImage(srcBitmap);
return;
}
if (analyzer == null) {
return;
}
// Create an MLFrame by using the bitmap.
MLFrame frame = new MLFrame.Creator().setBitmap(srcBitmap).create();
Task<MLTextImageSuperResolution> task = analyzer.asyncAnalyseFrame(frame);
task.addOnSuccessListener(new OnSuccessListener<MLTextImageSuperResolution>() {
public void onSuccess(MLTextImageSuperResolution result) {
// success.
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
setImage(result.getBitmap());
ImageSetupFlag = true;
}
})
.addOnFailureListener(new OnFailureListener() {
public void onFailure(Exception e) {
// failure.
if (e instanceof MLException) {
MLException mlException = (MLException) e;
// Get the error code, developers can give different page prompts according to the error code.
int errorCode = mlException.getErrCode();
// Get the error message, developers can combine the error code to quickly locate the problem.
String errorMessage = mlException.getMessage();
Toast.makeText(getApplicationContext(), "Error:" + errorCode + " Message:" + errorMessage, Toast.LENGTH_SHORT).show();
} else {
// Other exception。
Toast.makeText(getApplicationContext(), "Failed:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private void setImage(final Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
private void createAnalyzer() {
analyzer = MLTextImageSuperResolutionAnalyzerFactory.getInstance().getTextImageSuperResolutionAnalyzer();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (srcBitmap != null) {
srcBitmap.recycle();
}
release();
}
}
More details, you can check https://forums.developer.huawei.com/forumPortal/en/topicview?tid=0202388336667910498&fid=0101187876626530001
Which all image format is supported?

Integrating HUAWEI Analytics Kit Using Unity

This document describes how to integrate Analytics Kit using the official Unity asset. After the integration, your app can use the services of this Kit on HMS mobile phones.
For details about Analytics Kit, please visit HUAWEI Developers.
1.1 Preparations​1.1.1 Importing Unity Assets​1.1.2 Generating .gradle Files​1. Enable project gradle.
Go to Edit > Project Settings > Player in Unity, click the Android icon, and go to Publishing Settings > Build.
Enable Custom Base Gradle Template.
Enable Custom Launcher Gradle Template.
Enable Custom Main Gradle Template.
Enable Custom Main Manifest.
{
"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"
}
2. Signature
You can use an existing keystore file or create a new one to sign your app.
Go to Edit > Project Settings > Player in Unity, click the Android icon, and go to Publishing Settings > Keystore Manager > Keystore... > Create New.
Enter the password when you open Unity. Otherwise, you cannot build the APK.
1.1.3 Configuring .gradle Files and the AndroidManifest.xml File​1. Configure the BaseProjectTemplate.gradle file.
Code:
<p style="line-height: 1.5em;">Configure the Maven repository address.
buildscript {
repositories {**ARTIFACTORYREPOSITORY**
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
// If you are changing the Android Gradle Plugin version, make sure it is compatible with the Gradle version preinstalled with Unity.
// For the Gradle version preinstalled with Unity, please visit https://docs.unity3d.com/Manual/android-gradle-overview.html.
// For the official Gradle and Android Gradle Plugin compatibility table, please visit https://developer.android.com/studio/releases/gradle-plugin#updating-gradle.
// To specify a custom Gradle version in Unity, go do Preferences > External Tools, deselect Gradle Installed with Unity (recommended), and specify a path to a custom Gradle version.
classpath 'com.android.tools.build:gradle:3.4.0'
classpath 'com.huawei.agconnect:agcp:1.2.1.301'
**BUILD_SCRIPT_DEPS**
}
repositories {**ARTIFACTORYREPOSITORY**
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
flatDir {
dirs "${project(':unityLibrary').projectDir}/libs"
}
}</p>
2. Configure the launcherTemplate.gradle file.
Code:
<p style="line-height: 1.5em;">// Generated by Unity. Remove this comment to prevent overwriting when exporting again.
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation project(':unityLibrary')
implementation 'com.huawei.hms:hianalytics:5.1.0.300'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.huawei.agconnect:agconnect-core:1.2.0.300'
}</p>
3. Configure the mainTemplate.gradle file.
Code:
<p style="line-height: 1.5em;">apply plugin: 'com.android.library'
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.huawei.agconnect:agconnect-core:1.2.0.300'
implementation 'com.huawei.hms:hianalytics:5.0.0.301'
**DEPS**}</p>
4. Configure the AndroidManifest.xml file.
Code:
<p style="line-height: 1.5em;"><?xml version="1.0" encoding="utf-8"?>
<!-- Generated by Unity. Remove this comment to prevent overwriting when exporting again. -->
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.unity3d.player"
xmlns:tools="http://schemas.android.com/tools">
<application>
<activity android:name="com.hms.hms_analytic_activity.HmsAnalyticActivity"
android:theme="@style/UnityThemeSelector">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="unity.cn"
android:scheme="https" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
</application></p>
1.1.4 Adding the agconnect-services.json File​1. Create an app by following instructions in Creating an AppGallery Connect Project and Adding an App to the Project.
Run keytool -list -v -keystore C:\TestApp.keyStore to generate the SHA-256 certificate fingerprint based on the keystore file of the app. Then, configure the fingerprint in AppGallery Connect.
2. Download the agconnect-services.json file and place it in the Assets/Plugins/Android directory of your Unity project.
1.1.5 Enabling HUAWEI Analytics​For details, please refer to the development guide.
1.1.6 Adding the HmsAnalyticActivity.java File​1. Destination directory:
2. File content:
Code:
<p style="line-height: 1.5em;">package com.hms.hms_analytic_activity;
import android.os.Bundle;
import com.huawei.hms.analytics.HiAnalytics;
import com.huawei.hms.analytics.HiAnalyticsTools;
import com.unity3d.player.UnityPlayerActivity;
import com.huawei.agconnect.appmessaging.AGConnectAppMessaging;
import com.huawei.hms.aaid.HmsInstanceId;
import com.hw.unity.Agc.Auth.ThirdPartyLogin.LoginManager;
import android.content.Intent;
import java.lang.Boolean;
import com.unity3d.player.UnityPlayer;
import androidx.core.app.ActivityCompat;
public class HmsAnalyticActivity extends UnityPlayerActivity {
private AGConnectAppMessaging appMessaging;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HiAnalyticsTools.enableLog();
HiAnalytics.getInstance(this);
appMessaging = AGConnectAppMessaging.getInstance();
if(appMessaging != null){
appMessaging.setFetchMessageEnable(true);
appMessaging.setDisplayEnable(true);
appMessaging.setForceFetch();
}
LoginManager.getInstance().initialize(this);
boolean pretendCallMain = false;
if(pretendCallMain == true){
main();
}
}
private static void callCrash() {
throwCrash();
}
private static void throwCrash() {
throw new NullPointerException();
}
public static void main(){
JavaCrash();
}
private static void JavaCrash(){
new Thread(new Runnable() {
@Override
public void run() { // Sub-thread.
UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
callCrash();
}
});
}
}).start();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
LoginManager.getInstance().onActivityResult(requestCode, resultCode, data);
}
}</p>
1.2 App Development with the Official Asset​1.2.1 Sample Code​
Code:
<p style="line-height: 1.5em;">using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HuaweiHms;
public class AnalyticTest : MonoBehaviour
{
private HiAnalyticsInstance instance;
private int level = 0;
// Start() is called before the first frame update.
void Start()
{
}
// Update() is called once per frame.
void Update()
{
}
public AnalyticTest()
{
// HiAnalyticsTools.enableLog();
// instance = HiAnalytics.getInstance(new Context());
}
public void AnalyticTestMethod()
{
HiAnalyticsTools.enableLog();
instance = HiAnalytics.getInstance(new Context());
instance.setAnalyticsEnabled(true);
Bundle b1 = new Bundle();
b1.putString("test", "123456");
instance.onEvent("debug", b1);
}
public void SetUserId()
{
instance.setUserId("unity test Id");
// Util.showToast("userId set");
}
public void SendProductId()
{
Bundle b1 = new Bundle();
b1.putString(HAParamType.PRODUCTID, "123456");
instance.onEvent(HAEventType.ADDPRODUCT2CART, b1);
// Util.showToast("product id set");
}
public void SendAnalyticEnable()
{
enabled = !enabled;
instance.setAnalyticsEnabled(enabled);
// TestTip.Inst.ShowText(enabled ? "ENABLED" : "DISABLED");
}
public void CreateClearCache()
{
instance.clearCachedData();
// Util.showToast("Clear Cache");
}
public void SetFavoriteSport()
{
instance.setUserProfile("favor_sport", "running");
// Util.showToast("set favorite");
}
public void SetPushToken()
{
instance.setPushToken("fffff");
// Util.showToast("set push token as ffff");
}
public void setMinActivitySessions()
{
instance.setMinActivitySessions(10000);
// Util.showToast("setMinActivitySessions 10000");
}
public void setSessionDuration()
{
instance.setSessionDuration(900000);
// Util.showToast("setMinActivitySessions 900000");
}
public void getUserProfiles()
{
getUserProfiles(false);
getUserProfiles(true);
}
public void getUserProfiles(bool preDefined)
{
var profiles = instance.getUserProfiles(preDefined);
var keySet = profiles.keySet();
var keyArray = keySet.toArray();
foreach (var key in keyArray)
{
// TestTip.Inst.ShowText($"{key}: {profiles.getOrDefault(key, "default")}");
}
}
public void pageStart()
{
instance.pageStart("page test", "page test");
// TestTip.Inst.ShowText("set page start: page test, page test");
}
public void pageEnd()
{
instance.pageEnd("page test");
// TestTip.Inst.ShowText("set page end: page test");
}
public void enableLog()
{
HiAnalyticsTools.enableLog(level + 3);
// TestTip.Inst.ShowText($"current level {level + 3}");
level = (level + 1) % 4;
}
}</p>
1.2.2 Testing the APK​1. Generate the APK.
Go to File > Build Settings > Android, click Switch Platform, and then Build And Run.
2. Enable the debug mode.
3. Go to the real-time overview page of Analytics Kit in AppGallery Connect.
Sign in to AppGallery Connect and click My projects. Select one of your projects and go to HUAWEI Analytics > Overview > Real-time overview.
4. Call AnalyticTestMethod() to display analysis events reported.
Our official website
Demo for Analytics Kit
Our Development Documentation page, to find the documents you need:
Android SDK
Web SDK
Quick APP SDK
If you have any questions about HMS Core, you can post them in the community on the HUAWEI Developers website or submit a ticket online.
We’re looking forward to seeing what you can achieve with HUAWEI Analytics!
More Information
To join in on developer discussion forums
To download the demo app and sample code
For solutions to integration-related issues
Checkout in forum

Categories

Resources