QUICK_EXAMPLE.java 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. // ============================================
  2. // 快速示例:在现有 Ability 中调用 JS Ability
  3. // ============================================
  4. // 1. 在你的 Ability 中导入必要的类
  5. import ohos.aafwk.content.Intent;
  6. import ohos.aafwk.content.Operation;
  7. import com.fujica.abk.utils.JsAbilityHelper;
  8. // ============================================
  9. // 示例 1:在按钮点击事件中启动 JS Ability
  10. // ============================================
  11. public class MainAbilitySlice extends AbilitySlice {
  12. @Override
  13. public void onStart(Intent intent) {
  14. super.onStart(intent);
  15. // 创建一个按钮
  16. Button button = new Button(this);
  17. button.setText("打开 JS 页面");
  18. button.setClickedListener(component -> {
  19. // 调用 JS Ability
  20. JsAbilityHelper.startJsAbility(
  21. getAbility(), // 当前 Ability
  22. "com.fujica.abk", // 你的应用包名
  23. "com.fujica.abk.JsAbility", // JS Ability 名称
  24. "Hello from Java!", // 传递的消息
  25. "测试数据" // 传递的数据
  26. );
  27. });
  28. // 添加到界面
  29. // ... 你的布局代码
  30. }
  31. }
  32. // ============================================
  33. // 示例 2:手动创建 Intent 启动(不使用工具类)
  34. // ============================================
  35. public void startJsAbilityManually() {
  36. // 创建 Intent
  37. Intent intent = new Intent();
  38. // 设置目标 Ability
  39. Operation operation = new Intent.OperationBuilder()
  40. .withDeviceId("") // 空字符串表示本设备
  41. .withBundleName("com.fujica.abk") // 应用包名
  42. .withAbilityName("com.fujica.abk.JsAbility") // JS Ability 完整名称
  43. .build();
  44. intent.setOperation(operation);
  45. // 添加参数
  46. intent.setParam("message", "Hello from Java");
  47. intent.setParam("data", "测试数据");
  48. intent.setParam("userId", 12345);
  49. intent.setParam("isVip", true);
  50. // 启动 Ability
  51. startAbility(intent);
  52. }
  53. // ============================================
  54. // 示例 3:启动 JS Ability 并接收返回结果
  55. // ============================================
  56. public class MyAbility extends Ability {
  57. private static final int REQUEST_CODE = 1001;
  58. // 启动 JS Ability
  59. public void callJsAbilityForResult() {
  60. Intent intent = new Intent();
  61. Operation operation = new Intent.OperationBuilder()
  62. .withDeviceId("")
  63. .withBundleName("com.fujica.abk")
  64. .withAbilityName("com.fujica.abk.JsAbility")
  65. .build();
  66. intent.setOperation(operation);
  67. intent.setParam("action", "getData");
  68. // 启动并等待返回结果
  69. startAbilityForResult(intent, REQUEST_CODE);
  70. }
  71. // 接收返回结果
  72. @Override
  73. protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
  74. super.onAbilityResult(requestCode, resultCode, resultData);
  75. if (requestCode == REQUEST_CODE && resultData != null) {
  76. // 获取 JS Ability 返回的数据
  77. String status = resultData.getStringParam("status");
  78. String data = resultData.getStringParam("data");
  79. long timestamp = resultData.getLongParam("timestamp", 0);
  80. // 处理返回的数据
  81. HiLog.info(LABEL, "收到返回: status=" + status + ", data=" + data);
  82. // 更新 UI 或执行其他操作
  83. Toast.info(this, "收到 JS 返回的数据: " + data);
  84. }
  85. }
  86. }
  87. // ============================================
  88. // 示例 4:传递复杂 JSON 数据
  89. // ============================================
  90. public void sendJsonData() {
  91. // 创建 JSON 对象
  92. ZSONObject jsonData = new ZSONObject();
  93. jsonData.put("userId", "123456");
  94. jsonData.put("userName", "张三");
  95. jsonData.put("age", 25);
  96. jsonData.put("isVip", true);
  97. // 嵌套对象
  98. ZSONObject address = new ZSONObject();
  99. address.put("city", "北京");
  100. address.put("district", "朝阳区");
  101. jsonData.put("address", address);
  102. // 使用工具类发送
  103. JsAbilityHelper.startJsAbilityWithJson(
  104. this,
  105. "com.fujica.abk",
  106. "com.fujica.abk.JsAbility",
  107. jsonData
  108. );
  109. }
  110. // ============================================
  111. // 示例 5:在 JS 端接收和返回数据(index.js)
  112. // ============================================
  113. /*
  114. import featureAbility from '@ohos.ability.featureAbility';
  115. export default {
  116. data: {
  117. message: '',
  118. receivedData: ''
  119. },
  120. // 接收参数
  121. onInit() {
  122. console.info('JS Ability 启动');
  123. var context = featureAbility.getContext();
  124. context.getWant((error, want) => {
  125. if (error) {
  126. console.error('获取参数失败: ' + JSON.stringify(error));
  127. return;
  128. }
  129. // 获取 Java 传递的参数
  130. if (want.parameters) {
  131. this.message = want.parameters.message || '';
  132. this.receivedData = want.parameters.data || '';
  133. console.info('message: ' + this.message);
  134. console.info('data: ' + this.receivedData);
  135. // 如果传递了 JSON 数据
  136. if (want.parameters.jsonData) {
  137. var json = JSON.parse(want.parameters.jsonData);
  138. console.info('userId: ' + json.userId);
  139. console.info('userName: ' + json.userName);
  140. }
  141. }
  142. });
  143. },
  144. // 返回数据给 Java
  145. returnDataToJava() {
  146. var result = {
  147. resultCode: 1, // 返回码
  148. want: {
  149. parameters: {
  150. status: 'success',
  151. data: 'JS 处理后的数据',
  152. timestamp: new Date().getTime(),
  153. result: {
  154. code: 200,
  155. message: '操作成功'
  156. }
  157. }
  158. }
  159. };
  160. var context = featureAbility.getContext();
  161. context.terminateSelfWithResult(result, (error) => {
  162. if (error) {
  163. console.error('返回失败: ' + JSON.stringify(error));
  164. } else {
  165. console.info('成功返回数据并关闭');
  166. }
  167. });
  168. },
  169. // 简单关闭(不返回数据)
  170. close() {
  171. var context = featureAbility.getContext();
  172. context.terminateSelf();
  173. }
  174. }
  175. */
  176. // ============================================
  177. // 示例 6:完整的实战场景
  178. // ============================================
  179. public class OrderDetailAbility extends Ability {
  180. // 场景:从订单详情页面跳转到支付页面(JS 实现)
  181. private void gotoPaymentPage(String orderId, double amount) {
  182. Intent intent = new Intent();
  183. // 设置目标
  184. Operation operation = new Intent.OperationBuilder()
  185. .withBundleName("com.fujica.abk")
  186. .withAbilityName("com.fujica.abk.JsAbility")
  187. .build();
  188. intent.setOperation(operation);
  189. // 传递订单信息
  190. intent.setParam("page", "payment"); // 指定打开的页面
  191. intent.setParam("orderId", orderId);
  192. intent.setParam("amount", String.valueOf(amount));
  193. intent.setParam("fromPage", "orderDetail");
  194. // 启动支付页面并等待支付结果
  195. startAbilityForResult(intent, 2001);
  196. }
  197. @Override
  198. protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
  199. if (requestCode == 2001 && resultData != null) {
  200. // 处理支付结果
  201. String payStatus = resultData.getStringParam("payStatus");
  202. String orderId = resultData.getStringParam("orderId");
  203. if ("success".equals(payStatus)) {
  204. Toast.success(this, "支付成功!");
  205. // 刷新订单状态
  206. refreshOrderStatus(orderId);
  207. } else if ("failed".equals(payStatus)) {
  208. Toast.error(this, "支付失败");
  209. } else if ("cancelled".equals(payStatus)) {
  210. Toast.info(this, "已取消支付");
  211. }
  212. }
  213. }
  214. private void refreshOrderStatus(String orderId) {
  215. // 刷新订单状态的逻辑
  216. }
  217. }
  218. // ============================================
  219. // 重要提示
  220. // ============================================
  221. /*
  222. 1. 确保 config.json 中已注册 JS Ability
  223. 2. 包名和 Ability 名称必须完全匹配
  224. 3. 参数只能传递基本类型,复杂对象需要序列化为 JSON
  225. 4. 使用 startAbilityForResult 才能接收返回结果
  226. 5. JS 端使用 featureAbility.getContext() 获取上下文
  227. 6. JS 端使用 terminateSelfWithResult 返回数据
  228. */