欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > arkts bridge使用示例

arkts bridge使用示例

2025/2/2 19:37:50 来源:https://blog.csdn.net/taopi2001/article/details/145397510  浏览:    关键词:arkts bridge使用示例

接上一篇:arkui-x跨平台与android java联合开发-CSDN博客

本篇讲前端arkui如何与后端其他平台进行数据交互,接上一篇,后端os平台为Android java。

arkui-x框架提供了一个独特的机制:bridge。

1、前端接口定义实现

定义一个bridge的class,里面创建平台桥接实例,就可以实现各种bridge接口。

这里实现了一个getThirdAppInfo接口,获取后端第三方应用的信息。参数为两个string,返回一个promise数据。promise也就是JavaScript中用于处理异步操作的一种机制,详细说法这里就不展开了。

DevEco Studio工程

import bridge from '@arkui-x.bridge';export class ThirdPartyBridge {// 创建平台桥接实例private thirdPartyBridge = bridge?.createBridge && bridge.createBridge('xBridge');public getThirdAppInfo(defaultCfg: string, sysAppList: string) {return new Promise<string>((resolve, reject) => {this.thirdPartyBridge.callMethod('getThirdAppInfo', defaultCfg, sysAppList).then((result) => {console.log("getThirdAppInfo: ", result)resolve(result ? result.toString() : "")}).catch((err: Error) => {console.log('getThirdAppInfo err', JSON.stringify(err))})})}
}

2、后端数据获取接口

Android Studio工程

import ohos.ace.adapter.capability.bridge.BridgeManager;
import ohos.ace.adapter.capability.bridge.BridgePlugin;@SuppressLint("LogNotTimber")
public class Bridge extends BridgePlugin {private static final String TAG = Bridge.class.getSimpleName();public Bridge(Context context, String name, BridgeManager bridgeManager) {super(context, name, bridgeManager);}
。。。。。。public String getThirdAppInfo(String defaultCfg, String sysAppStr) throws JSONException {
//        Log.d("getThirdAppInfo", "---para1: " + defaultCfg + " para2: " + sysAppStr);List<JSONObject> retList = new ArrayList<>();
。。。。。。
// 实现获取数据的逻辑return retList.toString();}
。。。。。。
}

这里返回数据定义为json字符串,是为了方便前端解析。

3、前端调用bridge的业务代码实现

DevEco Studio工程

import { ThirdPartyBridge } from '../../bridge/ThirdPartyBridge';
import { DesktopShowCfg, ThirdPartyAppInfo } from '../../model/ThirdPartyAppInfo'export const getThirdAppInfo = async (defaultCfg: string, sysAppList: ThirdPartyAppInfo[]): Promise<ThirdPartyAppInfo[]> => {try {let sysAppStr: string = '[';
......// ThirdPartyAppInfo[]转为stringsysAppStr += ']'const bridge = new ThirdPartyBridge()const str = await bridge.getThirdAppInfo(defaultCfg, sysAppStr)console.log("---getThirdAppInfo", `获取第三方应用信息成功:` + str)let appInfoListList: ThirdPartyAppInfo[] = JSON.parse(str) as ThirdPartyAppInfo[]console.log("---getThirdAppInfo", `获取第三方应用信息,解析成功,app数量为:` + appInfoListList.length)return appInfoListList} catch (e) {console.log("---getThirdAppInfo", `获取第三方应用信息失败`, e.message)return []}
}

这里直接使用 JSON.parse(str) as ThirdPartyAppInfo[]方式实现了快速解析json。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com