Initialize the engine
Android
CubeInitParam cubeInitParam = CubeInitParam.getDefault();
MP.init(this, MPInitParam.obtain().addComponentInitParam(cubeInitParam));
iOS
[[CubeService sharedInstance] initWithConfig:config];
HarmonyOS
let config = CubeEngineConfig.obtain()
CubeEngine.getInstance().init(config);
Initialize engine parameters
Set the preset resource path
Android
CubeEngineConfig config = new CubeEngineConfig();
config.setResourcePath("cube");
cubeInitParam.setCubeEngineConfig(config)
iOS
CubeEngineConfig* config = [[CubeEngineConfig alloc] init];
[config setBundlePath:mockBundlePath];// The path to local cards.
HarmonyOS
config.setResourcePath("cube")
Set a custom JSAPI
Android
/**
* Registers a Cube JSAPI.
* @param cubeModuleModels
*/
public CubeInitParam setCubeModuleModels(Collection<CubeModuleModel> cubeModuleModels)
cubeInitParam.setCubeModuleModels(generateModuleModel())
iOS
NSDictionary *dic = @{@"MethodName": @"ImplementationClassName", @"abc": @"MPDemoModule"};
[[[CubeService sharedInstance] getEngine] registerModules:dic];
HarmonyOS
CubeEngine.getInstance().registerModule(new NativeCubeModule())
Set custom tags
Android
/**
* Registers a custom view (custom tag).
* @param cubeWidgetInfos
*/
public CubeInitParam setCubeWidgetInfos(Collection<CubeWidgetInfo> cubeWidgetInfos)
cubeInitParam.setCubeWidgetInfos(generateWidget())
iOS
CubeWidgetInfo *widgetInfo = [CubeWidgetInfo new];
widgetInfo.tag = @"custom-widget";
widgetInfo.className = [MPDemoCustomCardView class];
NSMutableArray *widgetArray = [NSMutableArray array];
[widgetArray addObject:widgetInfo];
[[[CubeService sharedInstance] getEngine] registerWidgets:[NSArray arrayWithArray:widgetArray]];
HarmonyOS
CubeEngine.getInstance().registerWidgets([customWidgetInfo])
Set an image downloader
Android
cubeInitParam.setImageHandler(new ICKImageHandler() {
@Override
public String loadImage(String s, int i, int i1, Map<String, Object> map, LoadImageListener loadImageListener) {
return null;
}
@Override
public void cancel(String s) {
}
iOS
Use CubeEngineConfig to intercept image downloads and customize image parameters. The client must conform to the CKImageHandler protocol and implement the listener method.
// Properties of the CubeEngineConfig card engine class
/// The image handler. If this is empty, the default internal implementation is used. Customize the handler.
@property (nonatomic, strong) id<CKImageHandler> imageHandler;// CKImageHandler.h
// CubePlatform
// Created by Joe on 2018/8/15.
// Copyright © 2018 mQuick. All rights reserved.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#ifndef CKImageHandler_h
#define CKImageHandler_h
extern NSString *const CKImageAppInstanceIDKey; // The AppInstanceID that corresponds to the triggered image loading.
extern NSString *const CKImagePageInstanceIDKey; // The PageInstanceID that corresponds to the triggered image loading.
extern NSString *const CKImageInstanceOptionKey; // The instance option. Added for the Falcon link.
typedef void(^CKImageHandlerCallback)(UIImage *image, NSError *error);
@protocol CKImageHandler <NSObject>
@required
/**
@param url The image download URL.
@param size The image size.
@param option Extension parameters that depend on the image download library.
@param callback The download callback. This callback is triggered after the download is complete.
@return Returns the unique ID of the download task.
*/
- (NSString *)fetchImage:(NSString *)url size:(CGSize)size option:(NSDictionary *)option callback:(CKImageHandlerCallback)callback;
@optional
/**
@param fetchID The task ID, which is the return value of fetchImage.
*/
- (void)cancel:(NSString*)fetchID;
@end@interface MPCubeManager () <CKImageHandler>
- (void)initEngine {
CubeEngineConfig *engineConfig = [[CubeEngineConfig alloc] init];
// Set the delegate.
engineConfig.imageHandler = self;
[[CubeService sharedInstance] initWithConfig:engineConfig];
}
- (NSString *)fetchImage:(NSString *)url size:(CGSize)size option:(NSDictionary *)option callback:(CKImageHandlerCallback)callback {
NSLog(@"Image URL: %@", url);
NSLog(@"Image extension parameters: %@", option);
return @"20211202";
}
HarmonyOS
config.setImageHandler(new MyImageHandler())
class MyImageHandler implements ICKImageHandler{
loadImage(context: Context, src: string, size: SizeOptions, option: Map<string, Object>,
callback: FalconLoadImageCallback): void {
}
}
Implement the loadImage method. The src parameter is the image URL, size contains the height and width, and callback returns a PixelMap.
Code example
class MyImageHandler implements ICKImageHandler {
loadImage(context: Context, src: string, size: SizeOptions, option: Map<string, Object>,
callback: FalconLoadImageCallback): void {
console.info("kf-wzh", "MyImageHandler loadImage")
// Obtain the context within the component to ensure that this.getUIContext().getHostContext() returns a UIAbilityContext.
// Get the resource manager.
const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
// 'test.jpg' is an example. Replace it with your own file. Otherwise, the imageSource fails to be created and subsequent operations cannot be performed.
resourceMgr.getRawFd('112233.jpg').then((rawFileDescriptor: resourceManager.RawFileDescriptor) => {
const imageSourceApi: image.ImageSource = image.createImageSource(rawFileDescriptor);
let decodingOptions: image.DecodingOptions = {
editable: true,
desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
index: 0
};
imageSourceApi.createPixelMap(decodingOptions, (err: BusinessError, pixelMap: image.PixelMap) => {
if (err) {
console.error(`Failed to create pixelMap. Code: ${err.code}, Message: ${err.message}`);
callback(false, null)
} else {
console.info('Succeeded in creating the pixelMap object.');
callback(true, pixelMap)
}
})
// callback(imageSourceApi.g)
}).catch((error: BusinessError) => {
console.error(`Failed to get RawFileDescriptor. Code: ${error.code}, Message: ${error.message}`);
})
}
}
Set an exception listener
Android
cubeInitParam.setExceptionListener(new CExceptionListener() {
@Override
public void onException(CExceptionInfo cExceptionInfo) {
}
})
iOS
Use CubeEngineConfig to listen for and catch frontend code exceptions. The client must conform to the CExceptionListener protocol and implement the listener method.
// Properties of the CubeEngineConfig card engine class
/// Exception listener
@property (nonatomic, strong) id<CExceptionListener> exceptionListener;// CExceptionListener proxy class
// CrystalExceptionProtocol.h
// CubeCrystal
// Created by hejin on 2021/9/10.
#import <Foundation/Foundation.h>
#import "CExceptionInfo.h"
#ifndef CExceptionListener_h
#define CExceptionListener_h
@protocol CExceptionListener <NSObject>
@required
/**
Exception listener
@param info The exception information.
*/
- (void)onException:(CExceptionInfo *)info;
@end@interface MPCubeManager () <CExceptionListener>
- (void)initEngine {
CubeEngineConfig *engineConfig = [[CubeEngineConfig alloc] init];
// Set the delegate.
engineConfig.exceptionListener = self;
[[CubeService sharedInstance] initWithConfig:engineConfig];
}
// Implement the listener method to print listener information.
- (void)onException:(CExceptionInfo *)info {
NSLog(@"Exception type: %lu", (unsigned long)info.type);
NSLog(@"Exception message: %@", info.message);
NSLog(@"Exception card ID: %@", info.cardUid);
NSLog(@"Exception information extension parameters: %@", info.extraInfo);
}
HarmonyOS
config.setExceptionListener(new MyCExceptionListener())
class MyCExceptionListener implements CExceptionListener{
onException(error: FalconExceptionInfo): void {
}
}
Set a log listener
Android
cubeInitParam.setLogHandler(new ICKLogHandler() {
@Override
public void log(Context context, int i, String s, String s1, Throwable throwable) {
// Android log
}
@Override
public void jsLog(Context context, String s) {
// JS log
}
iOS
CubeEngineConfig* config = [[CubeEngineConfig alloc] init];
config.logHandler = self;
[[CubeService sharedInstance] initWithConfig:config];
#pragma mark - CKLogHandler
- (void)nativeLog:(NSString *)log type:(CKLogType)type {
}
- (void)jsLog:(NSString *)log {
}
HarmonyOS
config.setLogHandler(new MyLogHandler())
class MyLogHandler implements ICKLogHandler{
log(message: string, level?: string | undefined): void {
}
}
Set an initialization callback
Android
cubeInitParam.setCubeInitCallback(new CubeInitParam.CubeInitCallback() {
@Override
public void onInit() {
}
@Override
public void onError(Exception e) {
}
})
iOS
Not supported.
HarmonyOS
Not supported.
Set the RpcHandler
Android
CubeInitParam cubeInitParam
= CubeInitParam.getDefault()
···
.setRpcHandler(new ICRpcHandler() {
@Override
public CKTemplateInfo.CKTemplateInfoResponse fetchTemplateInfo(List<CKTemplateInfo.CKTemplateInfoRequestParam> list) {
// CKRpcHandler() is the basic mPaaS implementation. Customers can extend it in ICRpcHandler.
return null;
}
})
iOS
// 1. Set the rpcHandler.
CubeEngineConfig *engineConfig = [[CubeEngineConfig alloc] init];
engineConfig.rpcHandler = self;
[[CubeService sharedInstance] initWithConfig:engineConfig];
// 2. Implement CTemplateInfoProtocol. For the return value, see the log printed during the default RPC request:
// rpc: templateInfo rpc result. You can also use the internal logic of the software development kit (SDK) when you implement your own RPC.
- (id)getTemplateInfoFromRpc:(NSArray *)params {
// 1. Use the custom RPC logic.
// 2. Use the default internal RPC logic of the SDK.
Class clazz = NSClassFromString(@"CrystalTemplateInfoHandler");
if (clazz) {
id<CTemplateInfoProtocol> handler = [[clazz alloc] init];
return [handler getTemplateInfoFromRpc:params];
}
return @{};
}
HarmonyOS
config.setRpcHandler(new MyRpcHandler())
class MyRpcHandler implements ICKRpcHandler {
rpc(reqs: RpcRequest[], callback: rpcResultCallback): void {
}
requestCards(reqs: CKTemplateInfoRequestParam[], callback: rpcResultCallback2): void {
}
}
Implement the requestCards method. Use the reqs: CKTemplateInfoRequestParam[] parameter to retrieve the requested card ID and version. The callback returns the message body as a CKTemplateInfoResponse object.
Code example
// The following content is obtained from reqs to request the following cards:
// Card 1: id: cube_harmony_txt, version: 1.0.X.X
// Card 2: id: cube_harmony_img, version: 1.0.X.X
// Assemble the card information to request the service and get the card data from the server. The following response body is returned:
{"missTemplateInfo":[cube_harmony_img-1.0.X.X],"resources":[{"fileMD5":"e91c9c75a8a1dcd8d7041945e2f837cd","fileUrl":"https://mcube-prod.mpaascloud.com/ALIPUBEDEDD87251609-default/cubekitResource/cube_harmony_txt/1.0.X.X/bin.zip","templateId":"cube_harmony_txt","templateResourceVersion":"1.0.0.0"}],"success":true}
// Then, perform the callback with the following content:
let data: CKTemplateInfo[] = []
data.push({
templateId: "cube_harmony_txt",
version: "1.0.0.0",
maxVersion: '',
minVersion: '',
sdkVersion: '',
description: '',
extend: '',
downLoadUrl: "https://mcube-prod.mpaascloud.com/ALIPUBEDEDD87251609-default/cubekitResource/cube_harmony_txt/1.0.0.0/bin.zip",
md5: "e91c9c75a8a1dcd8d7041945e2f837cd",
tickCount: '',
})
const miss = ['cube_harmony_img-1.0.0.0']
callback({
success: true,
message: 'success',
data: data,
missTemplateInfo:miss
})
该文章对您有帮助吗?