脚本宝典收集整理的这篇文章主要介绍了鸿蒙 JS FA 调用java PA简单实例,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
一. Java PA 端
需要继承 Ability,重写 onConnect 方法并返回 RemoteObject对象,业务逻辑在RemoteObject 的onRemoteRequest方法中处理。代码如下:
public class DemoService extends Ability {
MyRemote myRemote = new MyRemote();
//日志
PRivate static final HiLOGLabel LABEL_LOG = new HiLogLabel(3, 0xD001100, "Demo");
@override
protected IRemoteObject onConnect(Intent intent) {
//返回RemoteObject的对象
return myRemote.asObject();
}
class MyRemote extends RemoteObject implements IRemotebroker {
public MyRemote() {
suPEr("descriptor");
}
@Override
public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply,MessageOption option) throws RemoteException {
return true;
}
@Override
public IRemoteObject asObject() {
return this;
}
}
}
注意写完service类以后,需要 config.JSON 中注册service类,代码如下:
"abilities": [
{
"skills": [
{
"entities": [
"entity.System.home"
],
"actions": [
"action.system.home"
]
}
],
"visible": true,
"name": "com.jiakejian.myapplication.MainAbility",
"icon": "$media:icon",
"description": "$string:mainability_description",
"label": "$string:entry_MainAbility",
"type": "page",
"launchType": "standard"
},
{
"name": "com.jiakejian.myapplication.DemoService",
"icon": "$media:icon",
"description": "DemoService",
"type": "service"
}
],
二.JS FA端
<div class="container">
<button class="title" @click="onClick">
向java FA传递数据
</button>
</div>
js中需要添加 action 对象,相当于javaFA跳转中的intent ,并设为 异步方法。代码如下:
onClick:async function(){
//要传递的数据
VAR data = {
id:"001",
name:"xiaoli"
}
//action对象,相当于intent
var action = {};
//添加service所在的包名
action.bundleName = 'com.jiakejian.myapplication';
//添加service的类名
action.abilityName = 'com.jiakejian.myapplication.DemoService';
//添加messageCode ,用于区分其他的action
action.messageCode = 100;
//添加数据
action.data = data;
//跳转的activity的类型,0代表service
action.abilityType = 0;
//最重要的一步:跳转
var str = await FeatureAbility.callAbility(action);
//下面是处理 java FA 返回的数据
var result = JSON.parse(str);
console.log(result.id);
console.log(result.name);
}
三 .Java FA端 在RemoteObject对象的 onRemoteRequest方法中 处理数据并返回数据,代码如下:
@Override
public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply,MessageOption option) throws RemoteException {
switch (code) {
case 100:
String str = data.readString();
HiLog.info(LABEL_LOG, "str:"+str);
//添加返回数据
Map<String, Object> result = new HashMap<String, Object>();
result.put("id", "002");
result.put("name", "xiaohuang");
reply.writestring(ZSONObject.toZSONString(result));
break;
default:
return false;
}
return true;
}
执行结果如下:
以上是脚本宝典为你收集整理的鸿蒙 JS FA 调用java PA简单实例全部内容,希望文章能够帮你解决鸿蒙 JS FA 调用java PA简单实例所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。