How the components communicate? Secret ARouter routing mechanism

Interviewer: Is there used component-based, component-based communication how to do, ARouter have used it

Psychological Analysis: component-based architecture in general is often to test the contents of the components are more single application with our usual development mvc is not the same, is a component of fighting as a team, need to design complex components interact and communicate

Job seekers: from the assembly of the origin of the advantages of disadvantages start, leads to the final assembly of the weaknesses, communication components

1 componentization

1.1 Components of mind

  • APP version constant iteration, constantly adding new features, business has become increasingly complex, high maintenance costs.
  • Business coupled with high code more and more bloated, more than an internal team collaborative development difficult.
  • Android project compiled code when the computer will be very card, and because under a single project code coupling severe, each modified the code to be recompiled a package test, resulting in a very time-consuming.
  • Easy testing unit, changes a single service module, other modules of interest need not be focused on impact.

1.2 What are the components of

App is one of the components into a plurality Module, as shown below, each Module is an assembly (library may also be a basis for assembly dependence), we can develop during debugging component part separately, each between the components does not depend on , but they can call each other, when the final release of all the components in the form lib is dependent on the main app works and packaged into a apk.

1.3 Components of advantages

  • The general assembly of the module is independent, unified management to improve multiplexing, the page will be split into smaller size components, in addition to the internal components contained UI implementation, further comprising a data layer and logical layer.
  • Each project can be compiled separately, speed up compilation, packaged separately.
  • Modified within each project, it does not affect other projects.
  • Business library project can quickly split up, integrated into other App.
  • Iteration frequent business module using the module system, line of business R & D can interfere with each other, enhance cooperation efficiency, and control product quality, enhance stability.
  • Parallel development, team members only concerned with their small modular development, reduce the coupling to facilitate post-maintenance.

Communication of component 2

2.1 Components of communication

Components not directly dependent of each other, if the component A wants to call a method component B is impossible. Many developers because communication between the components of the complex is abandoned the use of components of

There are several ways of communication components:

####### 1. Local Radio

Local broadcast, which is LoacalBroadcastRecevier. More communication is carried out within the same application of the provisions of the different components of the system, the benefits of that: a broadcast transmission will only spread in their APP, will not leak to other APP, other APP can not send a broadcast to their APP without interference by other APP. Like local broadcast intercom communications, low cost, high efficiency, but there is a drawback is that all communication mechanisms entrusted both with the system, any steps that we can not intervene during the transmission, uncontrollable, commonly used ratio is not a component of the communication process high.

2. The inter-process AIDL

AIDL between processes. The size of that process, and we tend to be components of the communication process in the thread, besides AIDL communication is part of system-level communications, the underlying mechanism to Binder, although Android provides a template for us to achieve, but often difficult to understand user interaction is more complex , often do not apply during the communication of applied components.

3. anonymous shared memory

Anonymous shared memory. Such as using Sharedpreferences, in a scene in a multi-threaded, often thread-safe, which is a few more changes in store very little information, such as components in the configuration information, etc.

4.Intent Bundle transfer

Intent Bundle delivery. Including the transfer of explicit and implicit, explicit package name transfer needs clear path, components and assemblies often need to rely on each other, this departure from the components of the SOP (separation of concerns), if hidden away, not only would not be the package name path repeat, you need to define a set of rules, there is only one package name wrong path, investigation and it is also somewhat cumbersome, this approach tends to be more appropriate internal transfer between components, the external component dealing with other components use much scene.

2.2 is currently one of the mainstream approach is to introduce a third party, such as Base Module diagram.

3 ARouter communication frame assembly

About 3.1 ARouter

Alibaba is ARouter open-source Android platform to provide routing functionality to the page, middleware services, and advocate is simple enough. Mainly used as a component of the communication

GitHub:https://github.com/alibaba/ARouter

Foreword

        Intent intent = new Intent(mContext, XxxActivity.class);
 intent.putExtra("key","value");
 startActivity(intent);
 
 Intent intent = new Intent(mContext, XxxActivity.class);
 intent.putExtra("key","value"); startActivityForResult(intent, 666); 

The above piece of code in Android development, the most common and most commonly used feature is the jump page, we often face the need to jump from a browser or other pages to your App App needs, but even simple page jumps, over time, will encounter some problems:

  1. Centralized management URL: Speaking of centralized management, always compare egg pain, collaborative development of people, when we all go AndroidManifest.xml defined in various IntentFilter, implicit Intent, eventually found in flooded AndroidManifest.xml a variety of Schame, various Path, often need to solve Path overlapping coverage, too Activity is exported, causing security risks and other issues

  2. Configurable poor: Manifest xml format limited to, writing cumbersome, complicated configuration, what can be defined from fewer

  3. Jump process can not intervene: Jump directly by way of Intent, process developers can not jump interventions, some of aspect-oriented things difficult to implement, say this very generic logic logon, Buried, in each sub-page judgment very unreasonable, after all activity has been instantiated

  4. Cross-module can not explicitly rely on: when App small scale, we will do the horizontal split App, in accordance with the business split into multiple sub-modules, between completely decoupled, App by packing process control function, so easy to deal with large multiplayer team collaboration, logic does not interfere with each other, this time to rely on implicit Intent jump, writing in trouble, success is difficult to control.

To solve this problem, we need to be able to decouple a simple, multi-function, customizable strong support to intercept routing logic components: We chose ARouter Alibaba, the lazy, the Chinese introduced directly attached ARouter document:

3.2 ARouter advantage

Understand its advantages from ARouter Github:

Parsing the URL standard supports direct jump, and automatically injected into the target parameter module supports multi-page works supports interceptors add multiple, custom interceptor order dependency injection support, may be used alone as a support frame dependency injection InstantRun support MultiDex (Google program) mapping relationship grouped in clusters, multi-level management, on-demand initialization allows users to assign local and global downgrade downgrade policy page, interceptors, and other components are automatically registered service framework supports a variety of ways to configure the transition animation support fully support the acquisition Fragment Kotlin and mixed typical applications:

URL mapping from the outside to the inside pages, and parameter passing and parsing the page jump across modules, the process of decoupling interception jump between modules, handling the landing, and other logic Buried

Cross-module API call, to do the reverse by controlling the decoupling components

Third, the typical application scenarios

  1. URL mapping from the outside to the inside pages, and parameter passing and analysis
  2. Cross-module page jump, between decoupling module
  3. Jump interception process, handling the landing, and other logic Buried
  4. Cross-module API calls, decoupling between modules (in the form of registered ARouter services, call each other through the interface)

Fourth, the basic functions

  1. Adding dependencies and configuration
  2. apply plugin: 'com.neenbedankt.android-apt'
buildscript {
 repositories {
 jcenter()
 }
 dependencies {
 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
 }
 }
 apt {
 arguments {
 moduleName project.getName();
 }
 }
 dependencies {
 apt 'com.alibaba:arouter-compiler:x.x.x'
 compile 'com.alibaba:arouter-api:x.x.x'
 ...
 }
Add comment
// 在支持路由的页面、服务上添加注解(必选)
 // 这是最小化配置,后面有详细配置
 @Route(path = "/test/1")
 public class YourActivity extend Activity { ... } 
Initialization SDK
ARouter.init(mApplication); // 尽可能早,推荐在Application中初始化

1. Operation // initiate route within use simple jump (jump through URL 'in order to use' in) ARouter.getInstance () build ( "/ test / 1") navigation ()..;

// 2. 跳转并携带参数
 ARouter.getInstance().build("/test/1")
 .withLong("key1", 666L)
 .withString("key3", "888") .navigation(); 

Fifth, advanced usage

Jump through URL

 // 新建一个Activity用于监听Schame事件
 // 监听到Schame事件之后直接传递给ARouter即可
 // 也可以做一些自定义玩法,比方说改改URL之类的
 // http://www.example.com/test/1
 public class SchameFilterActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 // 外面用户点击的URL
 Uri uri = getIntent().getData();
 // 直接传递给ARouter即可
 ARouter.getInstance().build(uri).navigation();
 finish();
 }
 }
 // AndroidManifest.xml 中 的参考配置
 <activity android:name=".activity.SchameFilterActivity">
 <!-- Schame --> <intent-filter> <data android:host="m.aliyun.com" android:scheme="arouter"/> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> </intent-filter> <!-- App Links --> <intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:host="m.aliyun.com" android:scheme="http"/> <data android:host="m.aliyun.com" android:scheme="https"/> </intent-filter> </activity> 

Use ARouter help resolve the argument types

// URL中的参数会默认以String的形式保存在Bundle中
 // 如果希望ARouter协助解析参数(按照不同类型保存进Bundle中)
 // 只需要在需要解析的参数上添加 @Param 注解
 @Route(path = "/test/1") public class Test1Activity extends Activity { @Param // 声明之后,ARouter会从URL中解析对应名字的参数,并按照类型存入Bundle public String name; @Param private int age; @Param(name = "girl") // 可以通过name来映射URL中的不同参数 private boolean boy; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); name = getIntent().getStringExtra("name"); age = getIntent().getIntExtra("age", -1); boy = getIntent().getBooleanExtra("girl", false); // 注意:使用映射之后,要从Girl中获取,而不是boy } } 

Open ARouter parameters automatically injected (experimental feature, not recommended, is developing a protection strategy)

// 首先在Application中重写 attachBaseContext方法,并加入ARouter.attachBaseContext();
 @Override
 protected void attachBaseContext(Context base) { super.attachBaseContext(base); ARouter.attachBaseContext(); } // 设置ARouter的时候,开启自动注入 ARouter.enableAutoInject(); // 至此,Activity中的属性,将会由ARouter自动注入,无需 getIntent().getStringExtra("xxx")等等 

Statement interceptor (interceptor jump process, cut out for something)

 // 比较经典的应用就是在跳转过程中处理登陆事件,这样就不需要在目标页重复做登陆检查
 // 拦截器会在跳转之间执行,多个拦截器会按优先级顺序依次执行
 @Interceptor(priority = 666, name = "测试用拦截器") public class TestInterceptor implements IInterceptor { /** * The operation of this interceptor. * * @param postcard meta * @param callback cb */ @Override public void process(Postcard postcard, InterceptorCallback callback) { ... callback.onContinue(postcard); // 处理完成,交还控制权 // callback.onInterrupt(new RuntimeException("我觉得有点异常")); // 觉得有问题,中断路由流程 // 以上两种至少需要调用其中一种,否则会超时跳过 } /** * Do your init work in this method, it well be call when processor has been load. * * @param context ctx */ @Override public void init(Context context) { } } 

Jump treatment results

 // 通过两个参数的navigation方法,可以获取单次跳转的结果
 ARouter.getInstance().build("/test/1").navigation(this, new NavigationCallback() {
 @Override public void onFound(Postcard postcard) { ... } @Override public void onLost(Postcard postcard) { ... } }); 

Custom global strategy downgrade

// 实现DegradeService接口,并加上一个Path内容任意的注解即可
 @Route(path = "/xxx/xxx") // 必须标明注解
 public class DegradeServiceImpl implements DegradeService { /** * Router has lost. * * @param postcard meta */ @Override public void onLost(Context context, Postcard postcard) { // do something. } /** * Do your init work in this method, it well be call when processor has been load. * * @param context ctx */ @Override public void init(Context context) { } } 

For more information on the target page statement

// 我们经常需要在目标页面中配置一些属性,比方说"是否需要登陆"之类的
 // 可以通过 Route 注解中的 extras 属性进行扩展,这个属性是一个 int值,换句话说,单个int有4字节,也就是32位,可以配置32个开关
 // 剩下的可以自行发挥,通过字节操作可以标识32个开关
 @Route(path = "/test/1", extras = Consts.XXXX) 

Use ARouter management services (a) exposure services

/**
 * 声明接口
 */
 public interface IService extends IProvider { String hello(String name); } /** * 实现接口 */ @Route(path = "/service/1", name = "测试服务") public class ServiceImpl implements IService { @Override public String hello(String name) { return "hello, " + name; } /** * Do your init work in this method, it well be call when processor has been load. * * @param context ctx */ @Override public void init(Context context) { } } 

Use ARouter Management Services (b) discovery services

1. 可以通过两种API来获取Service,分别是ByName、ByType
 IService service = ARouter.getInstance().navigation(IService.class); // ByType
 IService service = (IService) ARouter.getInstance().build("/service/1").navigation(); // ByName service.hello("zz"); 2. 注意:推荐使用ByName方式获取Service,ByType这种方式写起来比较方便,但如果存在多实现的情况时,SDK不保证能获取到你想要的实现 

Use ARouter management services (c) Management dependence

Can your business logic or sdk, initialized by ARouter service package in the init method of service in your sdk, sdk using a different service ARouter the call,
every service at the time of first use will be initialized, that is calling the init method.
So you can say goodbye to sort out a mess of various dependencies, as long as the calls to the service, then the service included in the sdk and so it has been initialized, and completely do not need to
be concerned about the initialization sequence of each sdk.

Sixth, more features

Other settings in the initialization

ARouter.openLog(); // 开启日志
ARouter.printStackTrace(); // 打印日志的时候打印线程堆栈

Detailed API description

 // 构建标准的路由请求
 ARouter.getInstance().build("/home/main").navigation();
 // 构建标准的路由请求,并指定分组
 ARouter.getInstance().build("/home/main", "ap").navigation(); // 构建标准的路由请求,通过Uri直接解析 Uri uri; ARouter.getInstance().build(uri).navigation(); // 构建标准的路由请求,startActivityForResult // navigation的第一个参数必须是Activity,第二个参数则是RequestCode ARouter.getInstance().build("/home/main", "ap").navigation(this, 5); // 直接传递Bundle Bundle params = new Bundle(); ARouter.getInstance() .build("/home/main") .with(params) .navigation(); // 指定Flag ARouter.getInstance() .build("/home/main") .withFlags(); .navigation(); // 觉得接口不够多,可以直接拿出Bundle赋值 ARouter.getInstance() .build("/home/main") .getExtra(); // 使用绿色通道(跳过所有的拦截器) ARouter.getInstance().build("/home/main").greenChannal().navigation(); 

Free way to receive information: View My Home

image.png
image.png

Guess you like

Origin www.cnblogs.com/Androidmm/p/11389155.html