在HarmonyOS NEXT开发中路由管理应该怎么做,有没有样例代码,是建议用router还是Navigation?

在HarmonyOS NEXT开发中路由管理应该怎么做,有没有样例代码,是建议用router还是Navigation?

阅读 780
avatarAI BotBETA

在HarmonyOS NEXT开发中,路由管理通常涉及到页面之间的跳转和传递数据。HarmonyOS提供了多种方式进行路由管理,其中比较常用的方式是使用AbilityRouter(即router)进行页面跳转管理。Navigation在HarmonyOS开发中并不是一个标准的组件或概念,因此更推荐使用AbilityRouter

下面是一个使用AbilityRouter进行页面跳转的简单示例代码:

示例代码

1. 定义路由表

首先,在应用的资源文件中(通常是config.json),定义路由表。这里假设有两个页面:MainAbilityDetailAbility

{
  "module": {
    "package": "com.example.myapplication",
    "abilities": [
      {
        "name": "com.example.myapplication.MainAbility",
        "label": "MainAbility",
        "icon": "$media:icon",
        "description": "$string:mainability_description"
      },
      {
        "name": "com.example.myapplication.DetailAbility",
        "label": "DetailAbility",
        "icon": "$media:icon",
        "description": "$string:detailability_description"
      }
    ],
    "routes": [
      {
        "path": "/main",
        "abilities": [
          {
            "name": "com.example.myapplication.MainAbility"
          }
        ]
      },
      {
        "path": "/detail",
        "abilities": [
          {
            "name": "com.example.myapplication.DetailAbility"
          }
        ]
      }
    ]
  }
}

2. 在代码中实现跳转

接下来,在MainAbility中实现跳转到DetailAbility的代码。

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.bundle.IBundleManager;
import ohos.rpc.RemoteException;

public class MainAbility extends Ability {
    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        // 创建Intent用于页面跳转
        Intent detailIntent = new Intent();
        try {
            IBundleManager bundleManager = getBundleManager();
            if (bundleManager != null) {
                String[] types = bundleManager.getAbilityTypes("/detail");
                if (types != null && types.length > 0) {
                    detailIntent.setElement(new ohos.aafwk.content.ElementName(this.getPackageName(), types[0], null));
                    startAbility(detailIntent);
                }
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

解释

  1. 定义路由表:在config.json中定义应用的路由表,指定路径和对应的Ability。
  2. 页面跳转:在代码中,通过创建Intent对象并设置目标Ability的ElementName来实现页面跳转。这里使用getBundleManager()获取IBundleManager实例,通过它获取目标Ability的类型(即Ability的名称),然后设置到Intent中,最后调用startAbility()方法实现跳转。

建议

在HarmonyOS NEXT开发中,建议使用AbilityRouter进行路由管理,因为它更符合HarmonyOS的架构和设计理念。同时,AbilityRouter提供了灵活和强大的页面跳转和数据传递能力,可以满足大多数应用的需求。

1 个回答

推荐使用Navigation。RouterModule模块包含全局的路由栈和路由表信息。路由栈是NavPathStack对象,该对象与Entry.hap的Navigation组件绑定,RouterModule通过持有NavPathStack管理Navigation组件的路由信息。路由表builderMap是Map结构,以key-vaule的形式存储了需要路由的页面组件信息,其中key是自定义的唯一路由名,value是WrappedBuilder对象,该对象包裹了路由名对应的页面组件。RouterModule模块的实现主要包含以下步骤:
1.定义路由表和路由栈。

export class RouterModule { 
  // WrappedBuilder支持@Builder描述的组件以参数的形式进行封装存储 
  static builderMap: Map<string, WrappedBuilder<[object]>> = new Map<string, WrappedBuilder<[object]>>(); 
  // 初始化路由栈,需要关联Navigation组件 
  static navPathStack: NavPathStack = new NavPathStack(); 
} 
  1. 路由表增加路由注册和路由获取方法,业务har模块通过路由注册方法将需要路由的页面组件委托给RouterModule管理。
export class RouterModule { 
  // ... 
  // 注册页面组件到路由表,builderName是路由名字,builder参数是包裹了页面组件的WrappedBuilder对象 
  public static registerBuilder(builderName: string, builder: WrappedBuilder<[object]>): void { 
    RouterModule.builderMap.set(builderName, builder); 
  } 
 
  // 获取路由表中指定的页面组件 
  public static getBuilder(builderName: string): WrappedBuilder<[object]> { 
    const builder = RouterModule.builderMap.get(builderName); 
    if (!builder) { 
      console.info('not found builder ' + builderName); 
    } 
    return builder as WrappedBuilder<[object]>; 
  } 
} 
export class RouterModule { 
  // ... 
  // 通过获取页面栈跳转到指定页面 
  public static async push(harName: string, builderName: string): Promise<void> { 
    // 动态导入页面所在har模块,避免业务har模块中显示依赖其他har模块,实现按需加载 
    await import(harName); 
    // 通过路由栈的方法,按路由名字进行路由跳转 
    RouterModule.navPathStack.pushPathByName(builderName, null); 
  } 
}