search
HomeWeb Front-endJS TutorialHow to solve the problem of Router cross-module jump
How to solve the problem of Router cross-module jumpJun 12, 2018 pm 04:16 PM
routerCross module

After starting a modular development project, a very important issue is the page jump problem. This article mainly introduces the example of Router solving the page jump under cross-module. Now I will share it with you and give you an example. refer to.

1. Foreword

After starting a modular development project, a very important issue is the page jump problem.

For details on modular development, please see my other article Android Modular Development Exploration.

It is precisely because the project is divided into modules that there is no dependency between the modules and they are invisible to each other. So what should we do if we jump from interface a of module A to interface b of module B?

2. Cross-module jump methods

Here we will first introduce these common jump methods:

  1. Show jump

  2. Implicit jump

  3. Scheme protocol jump

  4. ##Router Routing table solution

2.1 Display jump

Display jump is our most commonly used jump method: using Intent, passing in the current Activity context, and the class object of the target Activity are enough, as follows:

Intent intent = new Intent();
intent.setClass(mContext, GuideActivity.class);
startActivity(intent);

Obviously, this method can only be called when the target Activity is visible (Activity is under the same Module). Not suitable for jumping between modules.

2.2 Hidden jump

The hidden jump we are talking about here is that the intent does not set a class, but sets an Action or Category.

For example:

In the manifest file

<!--网页展示界面-->
<activity
  android:name="com.whaty.base.BaseWebViewActivity"
  android:hardwareAccelerated="true">
    <intent-filter>
      <category android:name="android.intent.category.DEFAULT" />
      <action android:name="com.whaty.base.BaseWebViewActivity" />
    </intent-filter>
</activity>

When jumping:

//创建一个隐式的 Intent 对象:Action 动作 
Intent intent = new Intent(); 
//设置 Intent 的动作为清单中指定的action 
intent.setAction("com.whaty.base.BaseWebViewActivity"); 
startActivity(intent);

2.3 scheme jump

If we define a URI for B page - wsc://home/bbb, and then serialize the shared messageModel into a Json string, then A only needs to assemble a jump protocol that conforms to the B page scheme. wsc://home/bbb?message={ “name”:”John”, “age”:31, “city”:”New York” }

In the manifest file, configure the data attribute and set Its host, path, scheme, etc.

<activity android:name=".ui.BbbActivity"
  <intent-filter>
    <category android:name="android.intent.category.DEFAULT" />
    <action android:name="android.intent.action.VIEW" />
    <data
      android:host="bbb"
      android:path="/home"
      android:scheme="wsc" />
  </intent-filter>
</activity>

When jumping:

final Uri uri = new Uri.Builder().authority("wsc").path("home/bbb").appendQueryParameter("message", new Gson().toJson(messageModel)).build();
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);

The above methods are not what we want. Next, we will introduce our Router solution.

3. Why use Router

Google provides two native routing solutions: explicit and implicit. However, in modular development, explicit Intent has the problem of direct dependence on classes, causing severe coupling between modules. Implicit Intent requires a large number of paths to be configured in the Manifest, making it difficult to expand (such as jump interception). In order to solve the above problems, we need to adopt a more flexible Router solution.

4. Implementation Ideas

The idea is as follows:

Use annotations to label aliases for each target Activity. When the application starts, all classes are scanned and the annotated activities are stored in the routing table.

When jumping, obtain the class object of the target Activity through the alias in the routing table, and use Intent to implement the jump.

5. Code implementation

5.1 Custom annotations

/**
 * Description: 路由跳转界面 注解
 * Created by jia on 2018/1/10.
 * 人之所以能,是相信能
 */
@Target(ElementType.TYPE) //注解作用于类型(类,接口,注解,枚举)
@Retention(RetentionPolicy.RUNTIME) //运行时保留,运行中可以处理
@Documented // 生成javadoc文件
public @interface Action {

  String DEFAULT = "js";

  String value() default DEFAULT;

}

For a detailed introduction to custom annotations, Please read my article Java Advanced Custom Annotations. No more to say here.

5.2 Annotate Activity

@Action("MainActivity")
public class MainActivity extends BaseActivity implements TabLayout.OnTabSelectedListener {

  ...
}

When creating an Activity, annotate it with the just customized annotation and annotate it with an alias.

5.3 Scanning at startup

private void getAllActivities(Context ctx){
  try {
    //通过资源路径获得DexFile
    DexFile e = new DexFile(ctx.getPackageResourcePath());
    Enumeration entries = e.entries();
    //遍历所有元素
    while(entries.hasMoreElements()) {
      String entryName = (String)entries.nextElement();
      //匹配Activity包名与类名
      if(entryName.contains("activity") && entryName.contains("Activity")) {
        //通过反射获得Activity类
        Class entryClass = Class.forName(entryName);
        if(entryClass.isAnnotationPresent(Action.class)) {
          Action action = (Action)entryClass.getAnnotation(Action.class);
          this.map.put(action.value(), entryClass);
        }
      }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}

When the application starts, all classes under the package are scanned in Application. First, find the activity in the name (defined under the activity package), and then Activities marked with annotations are stored in the map.

5.4 Jump

/**
 * 页面跳转
 * @param activity
 * @param alias
 */
public void jumpActivity(Activity activity, String alias) throws ClassNotFoundException{
  if(map.containsKey(alias)) {
    Intent intent = new Intent(activity, map.get(alias));
    activity.startActivity(intent);
  } else {
    throw new ClassNotFoundException();
  }
}

Just pass in the alias of the target Activity when jumping (the alias here is the alias of the annotation).

Summary

In this way, the module dependency problem caused by jumping Activity is solved. Compared with the native solution, it is more scalable. However, this plan is only phased and there are still some problems. First of all, frequent use of reflection during the loading process will cause performance problems. Secondly, the alias of each Activity needs to be maintained uniformly, which increases the cost of collaboration. Still needs to be optimized.

Of course, there are many popular Router solutions on the market (such as Alibaba’s ARouter). Here is just an idea. If you have good suggestions, welcome to exchange and make progress together.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

About the use of Material in Angular2 (detailed tutorial)

How to use the Lodash method in Angular Do?

vue-router project actual combat (detailed tutorial)

How to control file drag and get the drag content function in js

The above is the detailed content of How to solve the problem of Router cross-module jump. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
React Router使用指南:如何实现前端路由控制React Router使用指南:如何实现前端路由控制Sep 29, 2023 pm 05:45 PM

ReactRouter使用指南:如何实现前端路由控制随着单页应用的流行,前端路由成为了一个不可忽视的重要部分。ReactRouter作为React生态系统中最受欢迎的路由库,提供了丰富的功能和易用的API,使得前端路由的实现变得非常简单和灵活。本文将介绍ReactRouter的使用方法,并提供一些具体的代码示例。安装ReactRouter首先,我们需

C++ 中如何在不同模块中调用函数?C++ 中如何在不同模块中调用函数?Apr 12, 2024 pm 03:54 PM

在C++中跨模块调用函数:声明函数:在目标模块的头文件中声明要调用的函数。实现函数:在源文件中实现函数。链接模块:使用链接器将包含函数声明和实现的模块链接在一起。调用函数:在需要调用的模块中包含目标模块的头文件,然后调用函数。

Vue Router Lazy-Loading路由的独特优势,如何优化页面性能?Vue Router Lazy-Loading路由的独特优势,如何优化页面性能?Sep 15, 2023 am 10:36 AM

VueRouter是Vue.js官方提供的路由管理插件,它可以帮助我们在Vue应用程序中实现页面导航和路由切换。其中的Lazy-Loading特性是VueRouter的一个独特优势,它可以极大地优化页面性能。在本文中,我们将介绍VueRouter的Lazy-Loading路由特性,并提供一些优化页面性能的实际代码示例。Lazy-Loading是指在需要

react router 不显示怎么办react router 不显示怎么办Dec 30, 2022 am 09:30 AM

react router不显示的解决办法:1、在父路由组件中加入browserRouter把router都包起来;2、使用“this.props.history.go()”进行组件刷新;3、在browserrouter参数里加上“forcerefresh={true}”;4、在“<Route>”里面写钩子函数,并在离开或进入此路由时调用即可。

vue3中如何使用router路由实现跳转传参vue3中如何使用router路由实现跳转传参May 16, 2023 am 10:49 AM

一、路由跳转1.首先在需要跳转的页面引入API&mdash;useRouterimport{useRouter}from&#39;vue-router&#39;2.在跳转页面定义router变量//先在setup中定义constrouter=useRouter()3.用router.push跳转页面//字符串router.push(&#39;home&#39;)//对象router.push({path:&#39;home&#39;})//

Vue Router中的路由懒加载是如何实现的?Vue Router中的路由懒加载是如何实现的?Jul 21, 2023 am 10:40 AM

VueRouter中的路由懒加载是如何实现的?在Vue开发中,我们通常使用VueRouter来实现页面之间的跳转和路由控制。当项目变得庞大时,我们可能会有很多路由页面需要加载,这样会导致整个项目的加载速度变慢。为了提高项目的性能,VueRouter提供了一种路由懒加载的机制。路由懒加载是指在路由页面被访问时才会进行加载,而不是在应用初始化时就加载所有路

在 Vue 项目中如何使用 Router 实现重定向功能在 Vue 项目中如何使用 Router 实现重定向功能Sep 15, 2023 am 08:36 AM

在Vue项目中如何使用Router实现重定向功能在一个Vue项目中,我们常常需要实现页面之间的跳转和重定向功能。而VueRouter提供了一个简单而强大的解决方案。本文将介绍如何在Vue项目中使用Router实现重定向功能,并给出具体的代码示例。安装VueRouter首先,我们需要在Vue项目中安装VueRouter。可

Vue Router Lazy-Loading路由:助力页面性能提升的趋势Vue Router Lazy-Loading路由:助力页面性能提升的趋势Sep 15, 2023 am 08:03 AM

VueRouter是Vue.js框架中的官方路由管理器。它允许开发者通过路由映射来切换页面内容,使得单页应用程序更加可控和易于维护。但是,在应用程序变得越来越复杂的情况下,路由的加载和解析可能会成为性能瓶颈。为了解决这个问题,VueRouter提供了一种懒加载路由的功能,即将路由的加载推迟到实际需要时。Lazy-loading(懒加载)是一种加载技术,它

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)