1. Environment and application information

The name of the version Integrated environment The device under test
Agconnect – database: 1.2.3.301 Unity 2019.4.17 f1c1 Glory Magic2 OPPO Reno2

AGC address: developer.huawei.com/consumer/cn…

2. Unity environment preparation:

Official documents:

Docs. Unity. Cn/cn/Packages…

1. Download Unity Hub and install Unity

Unity. Cn/releases. Download and install will not be introduced in detail.

2. Android environment configuration: See the screenshot below

Import the HuaweiServices Package.

Search for Huawei Services in Assect Store, find the AGC package, and click Import to Import the corresponding package.

3. AGC environment configuration

1. Set parameters on huawei AGC: Go back to the AGC console: Find the App created earlier:

Developer.huawei.com/consumer/cn…

2. Choose: My Project -> Build – Cloud database Click Open to open the cloud database, and then create the object type and storage area according to the requirements of Huawei documentation

Developer.huawei.com/consumer/cn…

On the object Type TAB page, click Add to add an object type named BookInfo as follows:

On the storage area page, click Add to add a storage area called QuickStartDemo

3. After the service is opened, return to the project setting interface and download the latest JSON file. Under my project – Project Settings – General – Apply, click agconnect-services.json to download

Put the json file you just downloaded into the Unity project Assets/Plugins/Android directory:

4. Set up the Android environment:

1. Enable Android custom listings and Gradle in Player-Publish Setting

2. Set the package name in Other Setting: Note that it must be consistent with the package name on the AG official website:

Level 3, configuration project gradle, the corresponding Assets \ Plugins \ Android path of baseProjectTmeplate gradle file, add the following content

allprojects {
        buildscript {
            repositories {
                maven { url 'https://developer.huawei.com/repo/' }
            }
        }
        dependencies {
            classpath 'com. Android. Tools. Build: gradle: 3.4.0'
            classpath 'com. Huawei. Agconnect: agcp: 1.4.2.301'
            **BUILD_SCRIPT_DEPS**
        }
    }
        repositories {
            maven { url 'https://developer.huawei.com/repo/'}}}Copy the code

4. Configure app-level Gradle and add the following contents to the launchertmeplate. gradle file corresponding to Assets\Plugins\Android:

apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
 
dependencies {
implementation project(':unityLibrary')Implementation 'com. Android. Support: appcompat - v7:28.0.0' implementation 'com. Huawei. Agconnect: agconnect - core: 1.2.0.300' Implementation "com. Huawei. Agconnect: agconnect - database: 1.2.3.301"}Copy the code

5. Return to the AGC interface and export the object type file:

1. Click “Export”, select JSON, and export the JSON file to Unity project Assets/Plugins/Android

2. Click “Export”, select Java, select “Android”, configure the package name, export the ZIP file and decompress it to the Unity project Assets/Plugins/Android directory

Create CloudDB file:

In Unity, go to CloudDB Kit – > CloudDB Settting on the menu bar.

1. JavaCode Package Name: specifies the Package Name configured when the Java file is exported

2, ObjectType JsonFile Path: select corresponding export json file: for example, my Path to ‘Assets/Plugins/android/model. The json’

Namespace: the Namespace used by the generated C# file

4. Export Path: save Path of exported C# files

5. Develop cloud database functions from scratch

1. Go to GameObject-UI-button and create a few buttons:

Click the button and select Add Component on the right to create and Add a Script file. The corresponding interface layout is as follows:

2. Code preinstallation and integration preparation:

using System;
using System.Collections;
using UnityEngine;
using HuaweiService;
using HuaweiService.CloudDB;
using HuaweiService.Auth;
using HuaweiServiceDemo;
 
public class testDBDemo : MonoBehaviour
{
    private static AGConnectCloudDB mCloudDB;
    private static CloudDBZone mCloudDBZone;
    private static CloudDBZoneConfig mConfig;
    private static CloudDBZoneQuery mQuery;
    private const string mClouudDBZoneName = "QuickStartDemo";
    private const string bookInfoClass = "com.huawei.agc.clouddb.quickstart.model.BookInfo";
    private const string testAllClass = "com.huawei.agc.clouddb.quickstart.model.TestAll";
    private static CloudDBZoneObjectList<BookInfo> mObjectList = new CloudDBZoneObjectList<BookInfo> ();
 
    // Successful callback
    public delegate void SuccessCallBack<T>(T o);
    public class HmsSuccessListener<T> :OnSuccessListener{
        public SuccessCallBack<T> CallBack;
        public HmsSuccessListener(SuccessCallBack<T> c){
            CallBack = c;
        }
        public void onSuccess(T arg0)
        {
            Debug.Log("OnSuccessListener onSuccess");
            if(CallBack ! =null) { CallBack.Invoke(arg0); }}public override void onSuccess(AndroidJavaObject arg0){
            Debug.Log("OnSuccessListener onSuccess");
            if(CallBack ! =null) { Type type = typeof(T); IHmsBase ret = (IHmsBase)Activator.CreateInstance(type); ret.obj = arg0; CallBack.Invoke((T)ret); }}}// Failed callback
    public delegate void FailureCallBack(HuaweiService.Exception e);
    public class HmsFailureListener : OnFailureListener
    {
        public FailureCallBack CallBack;
 
        public HmsFailureListener(FailureCallBack c)
        {
            CallBack = c;
        }
 
        public override void onFailure(HuaweiService.Exception arg0)
        {
            if(CallBack ! =null) { CallBack.Invoke(arg0); }}}// Start is called before the first frame update
    void Start(a)
    {
        login();
    }
 
    // Update is called once per frame
    void Update(a)
    {}}Copy the code

3. Integrated authentication service: Anonymous authentication is integrated here for convenience

public void login(a)
    {
        AGConnectAuth auth = AGConnectAuth.getInstance();
        auth.signInAnonymously().addOnSuccessListener(new HuaweiOnsuccessListener<SignInResult>((signresult) =>
        {
            Debug.Log("sign in successfully." + signresult.getUser().getUid());
 
        })).addOnFailureListener(new HuaweiOnFailureListener((e) =>
        {
            Debug.Log("sign in failed");
        }));
    }
Copy the code

6. Integrated cloud database interface

Initializing and creating object types

    public void CreateObjectType(a)
    {
        AGConnectCloudDB.initialize(new Context());
        mCloudDB = AGConnectCloudDB.getInstance();
        Debug.Log("CloudDBInstance: " + mCloudDB);
        try
        {
            mCloudDB.createObjectType(ObjectTypeInfoHelper.getObjectTypeInfo());
            Debug.Log("createObjectType:" + mCloudDB );
        }
        catch (System.Exception e)
        {
            Debug.Log("createObjectType: "+ e.Message); }}Copy the code

2. OpenCloudZOne: Open the storage area

    public void OpenCloudDBZone(a)
    {
        // Debug.Log("Start OpenCloudDBZone:" + mCloudDB );
        mConfig = new CloudDBZoneConfig("QuickStartDemo",
            CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
            CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
        mConfig.setPersistenceEnabled(true);
        
        Task openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
        openDBZoneTask.addOnSuccessListener(new HmsSuccessListener<CloudDBZone>((cloudDBZone) =>
        {
            mCloudDBZone = cloudDBZone;
            Debug.Log("open clouddbzone2 success");
        }))
        .addOnFailureListener(new HmsFailureListener((HuaweiService.Exception e) =>
        {
            Debug.Log("open clouddbzone2 failed " + e.toString());
        }));
    }
Copy the code

3. Insert data

    public void upsertBookInfo(a){
        if (mCloudDBZone == null)
        {
             Debug.Log("CloudDBZone is null, try re-open it");
            return;
        }
        var bookInfo = new BookInfo { Id = 4, BookName = "test4" };
 
        Task task = mCloudDBZone.executeUpsert(bookInfo);
        task.addOnSuccessListener(new HmsSuccessListener<int>((cloudDBZoneResult) =>
        {
             Debug.Log("upsert " + cloudDBZoneResult + " records");
        }))
Copy the code

4. Query and process data and display

    public void testQueryInfo (a) {
        mQuery = CloudDBZoneQuery.where (new AndroidJavaClass (bookInfoClass)).equalTo ("shadowFlag".true);
        if (mCloudDBZone == null || mQuery == null) {
            Debug.Log("CloudDBZone or CloudDBZoneQuery is null, try re-open it");
            return;
        }
        Task queryTask = mCloudDBZone.executeQuery (mQuery, CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
        queryTask.addOnSuccessListener (new HmsSuccessListener<CloudDBZoneSnapshot<BookInfo>> ((snapshot) => {
                processQueryResult (snapshot);
        }))
        .addOnFailureListener (new HmsFailureListener ((exception) => {
                Debug.Log ("Query book list from cloud failed: " + exception.toString ());
        }));
    }
 
    private void processQueryResult (CloudDBZoneSnapshot<BookInfo> snapshot) {
        mObjectList = snapshot.getSnapshotObjects ();
        List<BookInfo> bookInfoList = new List<BookInfo> ();
        try {
            string result = "";
            while (mObjectList.hasNext ()) {
                BookInfo bookInfo = mObjectList.next ();
                bookInfoList.add (bookInfo);
                result += $"{bookInfo.BookName} ";
            }
            Debug.Log ($"QueryResult: {result}");
 
        } catch (System.Exception e) {
            Debug.Log ($"QueryResult : {e.Message}");
        } finally{ snapshot.release (); }}Copy the code

7. Pack test

1. Click File — Build and Setting to enter the packaging page and switch the Android Platform on the page.

2. After selecting the corresponding device, click Build And Run

3. Then you can check the Unity log in Android Logcat.

Insert and delete data can be viewed on the AGC page.

For more details, please refer to:

Cloud database Demo: github.com/AppGalleryC…


The original link: developer.huawei.com/consumer/cn…

Original author: Mayism