Quick Start

Last Updated on : 2023-09-28 08:29:38download

This topic describes how to quickly get started using the MiniApp SDK with an Android project.

Initialize the SDK

When the app starts up, call the MiniApp SDK initialization API to run the MiniApp framework.

API description

/**
 * Initialize the miniapp
 */
ThingMiniAppClient
     .initialClient()
     .initialize();

Open a miniapp

The APIs used to manage a miniapp include but are not limited to the following:

  • Open a miniapp
  • Preload a miniapp
  • Clear miniapp cache

Dedicated APIs are provided to open a miniapp in different scenarios.

  • Open a miniapp by miniapp ID: used to open an official version of miniapp.
  • Open a miniapp by QR code scanning: used to open an official, development, trial, and IDE preview version of miniapp.
  • Open a miniapp by URL: used to open a specific page of an official version of miniapp.

Method 1: By miniapp ID

To open a miniapp, the system will first check if a cache exists on the local device.

  • If there is a cache, it will be loaded while the latest miniapp will be downloaded in the background.
  • If there is no cache, the miniapp will be downloaded and opened.

As per the update logic, if a new miniapp version is available, it will take effect the next time the miniapp is opened.

API description

/**
 * Open a miniapp by appId
 * @params context      The value cannot be empty.
 * @params appId        The miniapp ID. The value cannot be empty.
 * @params appVersion   The miniapp version. The value can be empty.
 * @params params       The service parameters. The value can be empty.
*/
fun openMiniAppByAppId(context: Context, appId : String, appVersion: String? = null, params: Bundle? = null)

Parameter description

Parameter name Meaning Required Description
appId Miniapp ID Yes You can find the miniapp ID on the Tuya IoT Development Platform.
appVersion Miniapp version No The specified miniapp version.
params Service parameters No The parameters included in the request.

Example

ThingMiniAppClient
    .coreClient()
    .openMiniAppByAppId(context, "tydhopggfziofo1h9h", null, null);

Method 2: By QR code scanning

Scan the QR code generated on the Tuya IoT Development Platform to read the content and call the respective API to open a miniapp.

API description

/**
 * Open a miniapp by QR code scanning
 * @params context  The value cannot be empty.
 * @params url      The QR code content. The value cannot be empty.
 * @pamras params   The service parameters. The value can be empty.
*/
fun openMiniAppByQrcode(context: Context, url : String, params: Bundle? = null)

Parameter description

Parameter name Meaning Required Description
url QR code content Yes The QR code contains the URL of the miniapp.
params Service parameters No The parameters included in the request.

Example

ThingMiniAppClient
    .coreClient()
    .openMiniAppByQrcode(context, "tuyaSmart--miniApp?url=godzilla://tydhopggfziofo1h9h", null);

Method 3: By URL

Open a specific page of a miniapp.

/**
 * Open a miniapp by URL
 * @params context   The value cannot be empty.
 * @params url      The URL of the page to open. The value cannot be empty.
 * @params params    The service parameters. The value can be empty.
*/
fun openMiniAppByUrl(context: Context, url : String, params: Bundle? = null)

Parameter description

Parameter name Meaning Required Description
url Miniapp URL Yes The URL should be specified in the format of godzilla://miniprogramId/pagePath.
params Service parameters No The parameters included in the request.

Example

ThingMiniAppClient
    .coreClient()
    .openMiniAppByUrl(context, "godzilla://tydhopggfziofo1h9h/pages/home/index", null);

Delete a miniapp

After a miniapp is used, the SDK will store the miniapp package and information to the local device. This uses the storage space of the device. You can call the following API to clear the miniapp and its cache.

API description

/**
 * Clear cache miniapp
*/
fun clearCache()

Example

ThingMiniAppClient
    .coreClient()
    .clearCache();

Preload a miniapp

Download the miniapp to the local device to speed up the startup process.

API description

/**
 *  Preload a miniapp, applying to the official version of miniapp.
 * @params appId  The miniapp ID, which can be found on the Tuya IoT Development Platform. The value cannot be empty.
*/
fun preloadMiniApp(appId: String)

Parameter description

Parameter name Meaning Required Description
appId Miniapp ID Yes You can find the miniapp ID on the Tuya IoT Development Platform.

Example

ThingMiniAppClient
    .coreClient()
    .preloadMiniApp("tydhopggfziofo1h9h");

Query runtime information

Obtain the runtime information about a miniapp to help troubleshoot issues.

API description

/**
 * Return the latest version of the base library.
*/
fun getJSSdkVersion(): String?

/**
 * Return the version of the miniapp container used by the SDK.
*/
fun getMiniAppContainerVersion() : String?

/**
 * Return the version of TTT-Kits that the app depends on.
*/
fun getMiniAppKitsVersion() : Map<String, String>?

/**
 * Whether to support debugging in vConsole.
 * @param enable true: Support; false: Not support
*/
fun vConsoleDebugEnable(enable : Boolean)

Example

// Query the version of the base library
ThingMiniAppClient
    .debugClient()
    .getJSSdkVersion();

// Query the version of the miniapp container
ThingMiniAppClient
    .debugClient()
    .getMiniAppContainerVersion();

// Query the version of TTT-Kits
ThingMiniAppClient
    .debugClient()
    .getMiniAppKitsVersion();

// Specify whether to support debugging in vConsole
ThingMiniAppClient
    .debugClient()
    .vConsoleDebugEnable(true);

Debug with vConsole

You can enable debugging to generate logs in vConsole for troubleshooting issues with the miniapp.

It is recommended to enable debugging only in the development stage and disable it when your project goes live in the production environment.

API description

/**
 * Specify whether to support debugging in vConsole
 * @param enable true: Support; false: Not support
*/
fun vConsoleDebugEnable(enable : Boolean)

Example

// Specify whether to support debugging on/off in vConsole
ThingMiniAppClient
    .debugClient()
    .vConsoleDebugEnable(true);

Customize API

MiniApp SDK offers a collection of pre-built APIs that can be called in the frontend code using ty.xxx({}).

If these APIs do not align with your business logic, you can tailor APIs to your needs.

Custom API

A custom API should inherit the abstract class BaseExtApiModule that defines the required data and methods.

API description

public abstract class BaseExtApiModule implements IExtApiMiniAppLifeCycle {

    /**
     * Implementation of asynchronous APIs, called in a child thread.
     *
     * @param params   API request parameters in the format {@link Map<String,Object>} to represent the parameter name and value.
     * @param callback  Result of the API request. The callback is invoked on success or failure to notify the frontend of the result.
     */
    @WorkerThread
    public abstract void invoke(@Nullable Map<String, Object> params, IGZLResultCallback<ExtApiResult> callback);

    /**
     * Implementation of synchronous APIs, called in a child thread.
     *
     * @param params API request parameters in the format {@link Map<String, Object>} to represent the parameter name and value.
     * @return {@link ExtApiResult}  Return result, the data parameter in this class cannot be obfuscated.
     */
    @WorkerThread
    public abstract @NonNull
    ExtApiResult invokeSync(@Nullable Map<String, Object> params);

    /**
     * The callback to invoke when the miniapp is active, usually after the pause state is released. You can override the subclass as needed.
     * The callback is invoked in the child thread.
     * */
    @Override
    @WorkerThread
    public void onMiniAppResume() {

    }

    /**
     * The callback to invoke when the miniapp is paused, such as moving to the background or overlaid by other native pages.  You can override the subclass as needed.
     * The callback is invoked in the child thread.
     * */
    @Override
    @WorkerThread
    public void onMiniAppPause() {

    }

    /**
     * The callback to invoke when the miniapp is destroyed. You can override the subclass as needed.
     * The callback is invoked in the child thread.
     * */
    @Override
    @WorkerThread
    public void onMiniAppDestroy() {

    }

}

Register custom API

// Create an entity class, following the ThingMiniAppExtApiProtocol 
ThingMiniAppClient.developClient()
                .addExtApiImpl("apiname", APIExtService.class)

static class APIExtService extends BaseExtApiModule{

        /**
         * Implementation of asynchronous APIs, called in a child thread.
         *
         * @param params   API request parameter in the format {@link Map<String,Object>} to represent the parameter name and value.
         * @param callback   Result of the API request. The callback is invoked on success or failure to notify the frontend of the result.
         */
        @Override
        public void invoke(@Nullable Map<String, Object> params, IGZLResultCallback<ExtApiResult> callback) {

        }

        /**
         * Implementation of synchronous APIs, called in a child thread.
         *
         * @param params  API request parameter in the format {@link Map<String, Object>} to represent the parameter name and value.
         * @return {@link ExtApiResult}  Return result, the data parameter in this class cannot be obfuscated.
         */
        @NonNull
        @Override
        public ExtApiResult invokeSync(@Nullable Map<String, Object> params) {
            return null;
        }
    }

Call custom API

A miniapp depends on MiniKit to call a custom API. The following three APIs in MiniKit are used.

  • ty.extApiCanIUse: Determine if the specified custom API is available.

    // Pass in the custom API name
    ty.extApiCanIUse({
        api: 'xxx',
        success:(res)=>{
            console.log(res.result)
        },
        fail:(err)=>{
            console.log(err)
        }
    })
    
  • ty.extApiInvoke: Call an asynchronous custom API.

    // Pass in the custom API name and parameters.
    ty.extApiInvoke({
        api: 'xxx',
        params: {},
        success:(res)=>{
            console.log(res.data)
        },
        fail:(err)=>{
            console.log(err)
        }
    })
    
  • ty.extApiInvokeSync: Call a synchronous custom API.

    // Pass in the custom API name and parameters.
    const data = ty.extApiInvokeSync({api: 'xxx', params: {}})