赞
踩
核心:
一. 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端
简单写了一个hml页面,添加了一个点击事件:
- <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;
- }
执行结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。