Home Web Front-end JS Tutorial Router solves page jumps under cross-modules

Router solves page jumps under cross-modules

Jan 13, 2018 am 09:24 AM
router solve page

The page jump problem is very important in modular development projects. This article mainly introduces the example of Router solving the page jump under cross-modules. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

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);
Copy after login

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

2.2 Hidden jump

The hidden jump we are talking about here does not set the class for the intent, but sets the 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>
Copy after login

When jumping:


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

2.3 scheme jump

If we define a URI for page B - 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 B's 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>
Copy after login

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);
Copy after login

The above methods are not ours If you want, let’s start introducing 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;

}
Copy after login

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 {

  ...
}
Copy after login

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

5.3 Scan 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();
  }
}
Copy after login

When the application starts, all classes under the package are scanned in Application, and first find the ones with activity in the name ( Defined under the activity package), and store the Activity with annotations 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();
  }
}
Copy after login

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 introduction. If you have good suggestions, welcome to exchange and make progress together.

Related recommendations:


vue realizes that the page jumps to the previous page after logging in. Example sharing

WeChat Xiaocheng clicks the text Methods to implement page jump function

HTML page jump and parameter passing issues

The above is the detailed content of Router solves page jumps under cross-modules. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to the problem that Win11 system cannot install Chinese language pack Solution to the problem that Win11 system cannot install Chinese language pack Mar 09, 2024 am 09:48 AM

Solution to the problem that Win11 system cannot install Chinese language pack With the launch of Windows 11 system, many users began to upgrade their operating system to experience new functions and interfaces. However, some users found that they were unable to install the Chinese language pack after upgrading, which troubled their experience. In this article, we will discuss the reasons why Win11 system cannot install the Chinese language pack and provide some solutions to help users solve this problem. Cause Analysis First, let us analyze the inability of Win11 system to

Five tips to teach you how to solve the problem of Black Shark phone not turning on! Five tips to teach you how to solve the problem of Black Shark phone not turning on! Mar 24, 2024 pm 12:27 PM

As smartphone technology continues to develop, mobile phones play an increasingly important role in our daily lives. As a flagship phone focusing on gaming performance, the Black Shark phone is highly favored by players. However, sometimes we also face the situation that the Black Shark phone cannot be turned on. At this time, we need to take some measures to solve this problem. Next, let us share five tips to teach you how to solve the problem of Black Shark phone not turning on: Step 1: Check the battery power. First, make sure your Black Shark phone has enough power. It may be because the phone battery is exhausted

The driver cannot be loaded on this device. How to solve it? (Personally tested and valid) The driver cannot be loaded on this device. How to solve it? (Personally tested and valid) Mar 14, 2024 pm 09:00 PM

Everyone knows that if the computer cannot load the driver, the device may not work properly or interact with the computer correctly. So how do we solve the problem when a prompt box pops up on the computer that the driver cannot be loaded on this device? The editor below will teach you two ways to easily solve the problem. Unable to load the driver on this device Solution 1. Search for "Kernel Isolation" in the Start menu. 2. Turn off Memory Integrity, and it will prompt "Memory Integrity has been turned off. Your device may be vulnerable." Click behind to ignore it, and it will not affect the use. 3. The problem can be solved after restarting the machine.

How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? Where is the automatically saved image when posting? Mar 22, 2024 am 08:06 AM

With the continuous development of social media, Xiaohongshu has become a platform for more and more young people to share their lives and discover beautiful things. Many users are troubled by auto-save issues when posting images. So, how to solve this problem? 1. How to solve the problem of automatically saving pictures when publishing on Xiaohongshu? 1. Clear the cache First, we can try to clear the cache data of Xiaohongshu. The steps are as follows: (1) Open Xiaohongshu and click the &quot;My&quot; button in the lower right corner; (2) On the personal center page, find &quot;Settings&quot; and click it; (3) Scroll down and find the &quot;Clear Cache&quot; option. Click OK. After clearing the cache, re-enter Xiaohongshu and try to post pictures to see if the automatic saving problem is solved. 2. Update the Xiaohongshu version to ensure that your Xiaohongshu

How to solve Chinese garbled characters in Linux How to solve Chinese garbled characters in Linux Feb 21, 2024 am 10:48 AM

The Linux Chinese garbled problem is a common problem when using Chinese character sets and encodings. Garbled characters may be caused by incorrect file encoding settings, system locale not being installed or set, and terminal display configuration errors, etc. This article will introduce several common workarounds and provide specific code examples. 1. Check the file encoding setting. Use the file command to view the file encoding. Use the file command in the terminal to view the encoding of the file: file-ifilename. If there is "charset" in the output

Share the method to solve the problem that PyCharm cannot be opened Share the method to solve the problem that PyCharm cannot be opened Feb 22, 2024 am 09:03 AM

Title: How to solve the problem that PyCharm cannot be opened. PyCharm is a powerful Python integrated development environment, but sometimes we may encounter the problem that PyCharm cannot be opened. In this article, we'll share some common workarounds and provide specific code examples. Hope this helps those who encounter this problem. Method 1: Clear the cache Sometimes PyCharm’s cache files may cause the program to fail to open normally. We can try clearing the cache to solve this problem. Tool

How to solve the problem of default gateway automatically disappearing How to solve the problem of default gateway automatically disappearing Feb 24, 2024 pm 04:18 PM

How to solve the problem that the default gateway disappears automatically. In modern society, the Internet has become an indispensable part of people's lives. Whether for work or entertainment, we all need stable network connections to complete various tasks. The default gateway is one of the key elements connecting the local network to the external Internet. However, sometimes we may encounter the problem that the default gateway disappears automatically, resulting in the inability to access the Internet. So, how should we solve this problem when the default gateway disappears? First, we should clarify the concept of default gateway. The default gateway is a network route

How to solve the problem that Huawei browser has stopped accessing this webpage How to solve the problem that Huawei browser has stopped accessing this webpage Feb 26, 2024 pm 01:28 PM

How to solve the problem that Huawei browser has stopped accessing this webpage? When using Huawei mobile browser to access certain websites, a prompt indicating that access is prohibited may appear, preventing users from browsing related content normally. This is very inconvenient for users. So, what should we do when we encounter a situation where access to the Huawei mobile browser website is prohibited? The editor below will provide you with solutions to the problem of prohibiting access to Huawei browser websites. I hope it will be helpful to you. Solution to the prohibition of access to the Huawei Browser website 1. After opening the Huawei mobile browser, click the three-dot icon below, and then click Settings. 2. After entering the settings, click [Security and Privacy] 3. Turn off the switch on the right side of [Safe Browsing] to remove website access restrictions. The above is the solution to the ban on Huawei browser website access.

See all articles