核心:
- 是通過FeatureAbility.callAbility(OBJECT)介面呼叫的,
一. 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;
}
執行結果如下:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/353415.html
標籤:其他
上一篇:從服務類呼叫方法時,SpringBoot@AutowiredNullPointerException
下一篇:js中6種變數宣告的方式
