| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271 |
- // ============================================
- // 快速示例:在现有 Ability 中调用 JS Ability
- // ============================================
- // 1. 在你的 Ability 中导入必要的类
- import ohos.aafwk.content.Intent;
- import ohos.aafwk.content.Operation;
- import com.fujica.abk.utils.JsAbilityHelper;
- // ============================================
- // 示例 1:在按钮点击事件中启动 JS Ability
- // ============================================
- public class MainAbilitySlice extends AbilitySlice {
-
- @Override
- public void onStart(Intent intent) {
- super.onStart(intent);
-
- // 创建一个按钮
- Button button = new Button(this);
- button.setText("打开 JS 页面");
- button.setClickedListener(component -> {
- // 调用 JS Ability
- JsAbilityHelper.startJsAbility(
- getAbility(), // 当前 Ability
- "com.fujica.abk", // 你的应用包名
- "com.fujica.abk.JsAbility", // JS Ability 名称
- "Hello from Java!", // 传递的消息
- "测试数据" // 传递的数据
- );
- });
-
- // 添加到界面
- // ... 你的布局代码
- }
- }
- // ============================================
- // 示例 2:手动创建 Intent 启动(不使用工具类)
- // ============================================
- public void startJsAbilityManually() {
- // 创建 Intent
- Intent intent = new Intent();
-
- // 设置目标 Ability
- Operation operation = new Intent.OperationBuilder()
- .withDeviceId("") // 空字符串表示本设备
- .withBundleName("com.fujica.abk") // 应用包名
- .withAbilityName("com.fujica.abk.JsAbility") // JS Ability 完整名称
- .build();
-
- intent.setOperation(operation);
-
- // 添加参数
- intent.setParam("message", "Hello from Java");
- intent.setParam("data", "测试数据");
- intent.setParam("userId", 12345);
- intent.setParam("isVip", true);
-
- // 启动 Ability
- startAbility(intent);
- }
- // ============================================
- // 示例 3:启动 JS Ability 并接收返回结果
- // ============================================
- public class MyAbility extends Ability {
-
- private static final int REQUEST_CODE = 1001;
-
- // 启动 JS Ability
- public void callJsAbilityForResult() {
- Intent intent = new Intent();
-
- Operation operation = new Intent.OperationBuilder()
- .withDeviceId("")
- .withBundleName("com.fujica.abk")
- .withAbilityName("com.fujica.abk.JsAbility")
- .build();
-
- intent.setOperation(operation);
- intent.setParam("action", "getData");
-
- // 启动并等待返回结果
- startAbilityForResult(intent, REQUEST_CODE);
- }
-
- // 接收返回结果
- @Override
- protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
- super.onAbilityResult(requestCode, resultCode, resultData);
-
- if (requestCode == REQUEST_CODE && resultData != null) {
- // 获取 JS Ability 返回的数据
- String status = resultData.getStringParam("status");
- String data = resultData.getStringParam("data");
- long timestamp = resultData.getLongParam("timestamp", 0);
-
- // 处理返回的数据
- HiLog.info(LABEL, "收到返回: status=" + status + ", data=" + data);
-
- // 更新 UI 或执行其他操作
- Toast.info(this, "收到 JS 返回的数据: " + data);
- }
- }
- }
- // ============================================
- // 示例 4:传递复杂 JSON 数据
- // ============================================
- public void sendJsonData() {
- // 创建 JSON 对象
- ZSONObject jsonData = new ZSONObject();
- jsonData.put("userId", "123456");
- jsonData.put("userName", "张三");
- jsonData.put("age", 25);
- jsonData.put("isVip", true);
-
- // 嵌套对象
- ZSONObject address = new ZSONObject();
- address.put("city", "北京");
- address.put("district", "朝阳区");
- jsonData.put("address", address);
-
- // 使用工具类发送
- JsAbilityHelper.startJsAbilityWithJson(
- this,
- "com.fujica.abk",
- "com.fujica.abk.JsAbility",
- jsonData
- );
- }
- // ============================================
- // 示例 5:在 JS 端接收和返回数据(index.js)
- // ============================================
- /*
- import featureAbility from '@ohos.ability.featureAbility';
- export default {
- data: {
- message: '',
- receivedData: ''
- },
-
- // 接收参数
- onInit() {
- console.info('JS Ability 启动');
-
- var context = featureAbility.getContext();
- context.getWant((error, want) => {
- if (error) {
- console.error('获取参数失败: ' + JSON.stringify(error));
- return;
- }
-
- // 获取 Java 传递的参数
- if (want.parameters) {
- this.message = want.parameters.message || '';
- this.receivedData = want.parameters.data || '';
-
- console.info('message: ' + this.message);
- console.info('data: ' + this.receivedData);
-
- // 如果传递了 JSON 数据
- if (want.parameters.jsonData) {
- var json = JSON.parse(want.parameters.jsonData);
- console.info('userId: ' + json.userId);
- console.info('userName: ' + json.userName);
- }
- }
- });
- },
-
- // 返回数据给 Java
- returnDataToJava() {
- var result = {
- resultCode: 1, // 返回码
- want: {
- parameters: {
- status: 'success',
- data: 'JS 处理后的数据',
- timestamp: new Date().getTime(),
- result: {
- code: 200,
- message: '操作成功'
- }
- }
- }
- };
-
- var context = featureAbility.getContext();
- context.terminateSelfWithResult(result, (error) => {
- if (error) {
- console.error('返回失败: ' + JSON.stringify(error));
- } else {
- console.info('成功返回数据并关闭');
- }
- });
- },
-
- // 简单关闭(不返回数据)
- close() {
- var context = featureAbility.getContext();
- context.terminateSelf();
- }
- }
- */
- // ============================================
- // 示例 6:完整的实战场景
- // ============================================
- public class OrderDetailAbility extends Ability {
-
- // 场景:从订单详情页面跳转到支付页面(JS 实现)
- private void gotoPaymentPage(String orderId, double amount) {
- Intent intent = new Intent();
-
- // 设置目标
- Operation operation = new Intent.OperationBuilder()
- .withBundleName("com.fujica.abk")
- .withAbilityName("com.fujica.abk.JsAbility")
- .build();
- intent.setOperation(operation);
-
- // 传递订单信息
- intent.setParam("page", "payment"); // 指定打开的页面
- intent.setParam("orderId", orderId);
- intent.setParam("amount", String.valueOf(amount));
- intent.setParam("fromPage", "orderDetail");
-
- // 启动支付页面并等待支付结果
- startAbilityForResult(intent, 2001);
- }
-
- @Override
- protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
- if (requestCode == 2001 && resultData != null) {
- // 处理支付结果
- String payStatus = resultData.getStringParam("payStatus");
- String orderId = resultData.getStringParam("orderId");
-
- if ("success".equals(payStatus)) {
- Toast.success(this, "支付成功!");
- // 刷新订单状态
- refreshOrderStatus(orderId);
- } else if ("failed".equals(payStatus)) {
- Toast.error(this, "支付失败");
- } else if ("cancelled".equals(payStatus)) {
- Toast.info(this, "已取消支付");
- }
- }
- }
-
- private void refreshOrderStatus(String orderId) {
- // 刷新订单状态的逻辑
- }
- }
- // ============================================
- // 重要提示
- // ============================================
- /*
- 1. 确保 config.json 中已注册 JS Ability
- 2. 包名和 Ability 名称必须完全匹配
- 3. 参数只能传递基本类型,复杂对象需要序列化为 JSON
- 4. 使用 startAbilityForResult 才能接收返回结果
- 5. JS 端使用 featureAbility.getContext() 获取上下文
- 6. JS 端使用 terminateSelfWithResult 返回数据
- */
|