初始化引擎
Android
CubeInitParam cubeInitParam = CubeInitParam.getDefault();
MP.init(this, MPInitParam.obtain().addComponentInitParam(cubeInitParam));iOS
[[CubeService sharedInstance] initWithConfig:config];鸿蒙
let config = CubeEngineConfig.obtain()
CubeEngine.getInstance().init(config);初始化引擎参数
设置预置资源路径
Android
CubeEngineConfig config = new CubeEngineConfig();
config.setResourcePath("cube");
cubeInitParam.setCubeEngineConfig(config)iOS
CubeEngineConfig* config = [[CubeEngineConfig alloc] init];
[config setBundlePath:mockBundlePath];//本地卡片的地址鸿蒙
config.setResourcePath("cube")设置自定义 JSAPI
Android
/**
* 注册 cube jsapi
* @param cubeModuleModels
*/
public CubeInitParam setCubeModuleModels(Collection<CubeModuleModel> cubeModuleModels)
cubeInitParam.setCubeModuleModels(generateModuleModel())iOS
NSDictionary *dic = @{@"方法名": @"实现的类名", @"abc": @"MPDemoModule"};
[[[CubeService sharedInstance] getEngine] registerModules:dic];鸿蒙
CubeEngine.getInstance().registerModule(new NativeCubeModule())设置自定义标签
Android
/**
* 注册自定义 view(自定义标签)
* @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]];鸿蒙
CubeEngine.getInstance().registerWidgets([customWidgetInfo])设置图片下载器
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
CubeEngineConfig 支持拦截 Image 下载,定制图片参数;客户端需要遵循 CKImageHandler 代理,实现监听方法。
// 卡片引擎类 CubeEngineConfig 的属性
/// 图片 handler,如果为空,则内部默认实现,建议自定义 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; // 触发加载图片对应的 AppInstanceID
extern NSString *const CKImagePageInstanceIDKey; // 触发加载图片对应的 PageInstanceID
extern NSString *const CKImageInstanceOptionKey; // instance option. 针对 falcon 链路添加
typedef void(^CKImageHandlerCallback)(UIImage *image, NSError *error);
@protocol CKImageHandler <NSObject>
@required
/**
@param url 图片下载 URL
@param size 图片尺寸
@param option 扩展参数,视图片下载库需求而定
@param callback 下载回调,下载完成后通过此接口回调
@return 返回表示本次下载任务的唯一 ID
*/
- (NSString *)fetchImage:(NSString *)url size:(CGSize)size option:(NSDictionary *)option callback:(CKImageHandlerCallback)callback;
@optional
/**
@param fetchID 任务 ID, fetchImage 的返回值
*/
- (void)cancel:(NSString*)fetchID;
@end@interface MPCubeManager () <CKImageHandler>
- (void)initEngine {
CubeEngineConfig *engineConfig = [[CubeEngineConfig alloc] init];
//设置 delegate
engineConfig.imageHandler = self;
[[CubeService sharedInstance] initWithConfig:engineConfig];
}
- (NSString *)fetchImage:(NSString *)url size:(CGSize)size option:(NSDictionary *)option callback:(CKImageHandlerCallback)callback {
NSLog(@"图片地址:%@", url);
NSLog(@"图片扩展参数:%@", option);
return @"20211202";
}鸿蒙
config.setImageHandler(new MyImageHandler())
class MyImageHandler implements ICKImageHandler{
loadImage(context: Context, src: string, size: SizeOptions, option: Map<string, Object>,
callback: FalconLoadImageCallback): void {
}
}主要实现 loadImage 方法,其中 src 为图片的地址,size 中有 height 和 width,callback 返回 PixelMap。
代码示例
class MyImageHandler implements ICKImageHandler {
loadImage(context: Context, src: string, size: SizeOptions, option: Map<string, Object>,
callback: FalconLoadImageCallback): void {
console.info("kf-wzh", "MyImageHandler loadImage")
// 请在组件内获取context,确保this.getUIContext().getHostContext()返回结果为UIAbilityContext。
// 获取resourceManager资源管理器。
const resourceMgr: resourceManager.ResourceManager = context.resourceManager;
//此处'test.jpg'仅作示例,请开发者自行替换,否则imageSource创建失败会导致后续无法正常执行。
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 is ${err.code},message is ${err.message}`);
callback(false, null)
} else {
console.info('Succeeded in creating pixelMap object.');
callback(true, pixelMap)
}
})
// callback(imageSourceApi.g)
}).catch((error: BusinessError) => {
console.error(`Failed to get RawFileDescriptor.code is ${error.code}, message is ${error.message}`);
})
}
}
设置异常监听
Android
cubeInitParam.setExceptionListener(new CExceptionListener() {
@Override
public void onException(CExceptionInfo cExceptionInfo) {
}
})iOS
CubeEngineConfig 支持异常监听,捕获前端代码异常。客户端需要遵循 CExceptionListener 代理,实现监听方法。
// 卡片引擎类 CubeEngineConfig 的属性
/// 异常监听
@property (nonatomic, strong) id<CExceptionListener> exceptionListener;// CExceptionListener 代理类
// 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
/**
异常监听
@param info 异常信息
*/
- (void)onException:(CExceptionInfo *)info;
@end@interface MPCubeManager () <CExceptionListener>
- (void)initEngine {
CubeEngineConfig *engineConfig = [[CubeEngineConfig alloc] init];
//设置 delegate
engineConfig.exceptionListener = self;
[[CubeService sharedInstance] initWithConfig:engineConfig];
}
//实现监听方法,打印监听信息
- (void)onException:(CExceptionInfo *)info {
NSLog(@"异常类型:%lu", (unsigned long)info.type);
NSLog(@"异常信息:%@", info.message);
NSLog(@"异常卡片 id:%@", info.cardUid);
NSLog(@"异常信息扩展参数:%@", info.extraInfo);
}鸿蒙
config.setExceptionListener(new MyCExceptionListener())
class MyCExceptionListener implements CExceptionListener{
onException(error: FalconExceptionInfo): void {
}
}设置日志监听
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 {
}
鸿蒙
config.setLogHandler(new MyLogHandler())
class MyLogHandler implements ICKLogHandler{
log(message: string, level?: string | undefined): void {
}
}设置初始化回调
Android
cubeInitParam.setCubeInitCallback(new CubeInitParam.CubeInitCallback() {
@Override
public void onInit() {
}
@Override
public void onError(Exception e) {
}
})iOS
暂不支持
鸿蒙
暂不支持
设置 RpcHandler
Android
CubeInitParam cubeInitParam
= CubeInitParam.getDefault()
···
.setRpcHandler(new ICRpcHandler() {
@Override
public CKTemplateInfo.CKTemplateInfoResponse fetchTemplateInfo(List<CKTemplateInfo.CKTemplateInfoRequestParam> list) {
// CKRpcHandler()是mpaas基础实现,客户在ICRpcHandler自行扩展
return null;
}
})iOS
//1、设置rpcHandler
CubeEngineConfig *engineConfig = [[CubeEngineConfig alloc] init];
engineConfig.rpcHandler = self;
[[CubeService sharedInstance] initWithConfig:engineConfig];
//2、实现CTemplateInfoProtocol,返回值可参考默认RPC请求时日志打印:
//rpc: templateaInfo rpc result,用户在自行实现RPC的基础上也可以使用SDK内部逻辑
- (id)getTemplateInfoFromRpc:(NSArray *)params {
//1、走自定义RPC逻辑
//2、走默认SDK内部RPC逻辑
Class clazz = NSClassFromString(@"CrystalTemplateInfoHandler");
if (clazz) {
id<CTemplateInfoProtocol> handler = [[clazz alloc] init];
return [handler getTemplateInfoFromRpc:params];
}
return @{};
}
鸿蒙
config.setRpcHandler(new MyRpcHandler())
class MyRpcHandler implements ICKRpcHandler {
rpc(reqs: RpcRequest[], callback: rpcResultCallback): void {
}
requestCards(reqs: CKTemplateInfoRequestParam[], callback: rpcResultCallback2): void {
}
}主要实现 requestCards 方法,通过 reqs: CKTemplateInfoRequestParam[] 获取请求的卡片 ID 和 Version,callback 返回信息的返回体即可,返回类型为 CKTemplateInfoResponse。
代码示例
我们从reqs 中获取了以下内容要请求以下卡片
卡片1:id:cube_harmony_txt,version:1.0.X.X
卡片2:id:cube_harmony_img,version:1.0.X.X
我们组装卡片信息请求服务,获取服务器中的卡片数据,得到以下返回体
{"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}
那么,我们就可以像以下的内容进行callback
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
})该文章对您有帮助吗?