Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build Android Page routing Framework in Alibaba-ARouter

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to build the Android page routing framework in Alibaba-ARouter. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

When you develop an App, you will always encounter all kinds of needs and businesses. at this time, you can get twice the result with half the effort by choosing a simple and easy-to-use wheel.

Preface

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)

In the above code, the most common and commonly used feature in Android development is page redirection. We often need to jump from browsers or other App to pages in our App, but even simple page jumps will encounter some problems over time:

Centralized URL management: when it comes to centralized management, it always hurts. When many people collaborate on development, everyone goes to AndroidManifest.xml to define all kinds of IntentFilter and use implicit Intent. Finally, it is found that AndroidManifest.xml is full of all kinds of Schame and all kinds of Path. It is often necessary to solve the problems of Path overlapping coverage, too much Activity being exported, security risks and so on.

Poor configurability: Manifest is limited to xml format, troublesome writing, complex configuration, and few things that can be customized

Can not intervene in the jump process: jump directly through the Intent way, the jump process developers can not intervene, some aspect-oriented things are difficult to implement, such as login, embedding this very general logic, in each sub-page judgment is very unreasonable, after all, activity has been instantiated

Cross-module cannot be explicitly dependent on: when the App is small in scale, we will split the App horizontally and into multiple sub-modules according to the business, which are completely decoupled. The App function is controlled through the packaging process, so it is convenient to deal with the cooperation of multiple people in a large team without interfering with each other logically. At this time, we can only rely on implicit Intent jump, writing trouble, and it is difficult to control whether it is successful or not.

The other wheel.

In order to solve the above problems, we need a routing component with decoupling, simplicity, multi-function, strong customization and supporting interception logic: we choose Alibaba's ARouter.

First, function introduction

Support parsing URL directly to jump, parsing parameters to Bundle by type, and supporting basic types of Java (*)

Standard page redirection within the application is supported, and API is close to Android native interface.

Support for use in multi-module projects, allowing separate packaging, as long as the package structure conforms to the Android package specification (*)

Support to insert custom intercept logic and custom intercept order in the jump process (*)

Support service hosting and obtain service instances through ByName,ByType to facilitate decoupling between interface-oriented development and cross-module invocation (*)

Mapping relationship is classified by group, multi-level management, initialization on demand, reduce memory consumption and improve query efficiency (*)

Support users to specify global downgrade policy

The result of a single jump can be obtained.

Rich API and customizability

Pages, interceptors and services managed by ARouter do not need to register with ARouter actively and passively discover

Support the Jack compilation chain launched by Android N

II. Unsupported features

Custom URL resolution rules (consider support)

Cannot dynamically load code modules and add routing rules (consider support)

Multipath support (do not want to support, seems to be the cause of all kinds of confusion)

Generate mapping relationship documents (consider support)

3. Typical application scenarios

Mapping from external URL to internal pages, and parameter passing and parsing

Cross-module page jump, decoupling between modules

Intercept the jump process, deal with landing, burying points and other logic

Cross-module API calls, decoupling between modules (register the form of ARouter services, call each other through interfaces)

IV. Basic functions

Add dependencies and configuration

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

/ / add comments on pages and services that support routing (required) / / this is a minimized configuration, followed by a detailed configuration @ Route (path = "/ test/1") public class YourActivity extend Activity {.}

Initialize SDK

ARouter.init (mApplication); / / as early as possible. Initialization in Application is recommended.

Initiate a routing operation

/ / 1. Simple jump within the application (in 'medium use' via URL) ARouter.getInstance (). Build ("/ test/1"). Navigation (); / 2. Jump and take the parameter ARouter.getInstance () .build ("/ test/1") .withlong ("key1", 666L) .withString ("key3", "888") .withstring ()

Add obfuscation rules (if Proguard is used)

-keep public class com.alibaba.android.arouter.routes.** {*;}

V. Advanced usage

Jump through URL

/ / create a new Activity to listen for Schame events / / pass it to ARouter directly after listening to Schame events. / / you can also do some custom games, such as modifying / / 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 () clicked by external users. / / pass it directly to ARouter to ARouter.getInstance (). Build (uri). Navigation (); finish ();}} / / reference configuration in AndroidManifest.xml

Use ARouter to assist in parsing parameter types

/ / the parameters in URL will be saved in Bundle as String by default / / if you want ARouter to assist in parsing the parameters (save in Bundle according to different types) / / you only need to add @ Param annotation @ Route (path = "/ test/1") public class Test1Activity extends Activity {@ Param / / to the parameters that need to be parsed, ARouter will parse the parameters with the corresponding name from URL and store them in Bundle public String name according to the type @ Param private int age; @ Param (name = "girl") / / different parameters in 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) / / Note: after using the mapping, get it from Girl instead of boy}}

Enable automatic injection of ARouter parameters (experimental feature, not recommended, protection strategy is being developed)

/ / first rewrite the attachBaseContext method in Application and add ARouter.attachBaseContext (); @ Override protected void attachBaseContext (Context base) {super.attachBaseContext (base); ARouter.attachBaseContext ();} / / enable automatic injection of ARouter.enableAutoInject () when setting ARouter; / / at this point, the properties in Activity will be automatically injected by ARouter without the need for getIntent () .getStringExtra ("xxx"), etc.

Declare the interceptor (intercept the jump process, face the aspect to cause trouble)

/ / A more classic application is to handle login events during the jump, so that there is no need to do repeated login checks on the target page. / / the interceptor will execute @ Interceptor (priority = 666, name = "test interceptor") public class TestInterceptor implements IInterceptor {/ * * The operation of this interceptor in order of priority. * * @ param postcard meta * @ param callback cb * / @ Override public void process (Postcard postcard, InterceptorCallback callback) {. Callback.onContinue (postcard); / / complete processing, return control / / callback.onInterrupt (new RuntimeException ("I feel a little abnormal"); / / if there is a problem, interrupt the routing process / / at least one of the above two needs to be called, otherwise it will time out to skip} / * 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) {}}

Process the jump result

/ / through the navigation method with two parameters, you can get the result of a single jump ARouter.getInstance () .build ("/ test/1") .jump (this, new NavigationCallback () {@ Override public void onFound (Postcard postcard) {.} @ Override public void onLost (Postcard postcard) {.}})

Custom global downgrade policy

/ / implement the DegradeService interface and add an arbitrary annotation of Path content to @ Route (path = "/ xxx/xxx") / / must be marked with 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) {}}

Declare more information for the target page

/ / We often need to configure some properties in the target page, such as "do you need to log in" / / can be extended through the extras attribute in the Route comments, which is an int value, in other words, a single int has 4 bytes, that is, 32 bits, can be configured with 32 switches / / the rest can be used on its own. 32 switches @ Route can be identified by byte operation (path = "/ test/1", extras = Consts.XXXX)

Using ARouter to manage services (1) expose services

/ * declare interface * / public interface IService extends IProvider {String hello (String name);} / * implement interface * / @ Route (path = "/ service/1", name = "testing service") 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) {}}

Using ARouter Management Services (2) Discovery Services

1. You can obtain Service through two kinds of API, namely ByName and ByType

IService service = ARouter.getInstance () .navigation (IService.class); / / ByType IService service = (IService) ARouter.getInstance () .build ("/ service/1") .navigation (); / / ByName service.hello ("zz")

two。 Note: it is recommended to use ByName to obtain Service,ByType, which is convenient to write, but if there are multiple implementations, SDK does not guarantee that you will get the desired implementation.

Using ARouter Management Services (3) Managing dependencies

You can wrap your business logic or sdk through ARouter service and initialize your sdk in the init method of service. Different sdk is called using ARouter's service. Each service is initialized when it is used for the first time, that is, the init method is called.

In this way, you can say goodbye to all kinds of messy dependency carding, as long as you can call this service, then the sdk contained in this service has been initialized, and you don't need to care about the initialization order of each sdk at all.

VI. More multi-functions

Other settings in initialization

ARouter.openLog (); / / Open log ARouter.printStackTrace (); / / print thread stack when printing log

Detailed API description

/ / build a standard routing request ARouter.getInstance (). Build ("/ home/main"). Navigation (); / / build a standard routing request and specify the packet ARouter.getInstance (). Build ("/ home/main", "ap"). Navigation (); / / build a standard routing request that parses Uri uri; ARouter.getInstance () .build (uri) .navigation () directly through Uri / / to build a standard routing request, the first parameter of startActivityForResult / / navigation must be Activity, and the second parameter must be RequestCode ARouter.getInstance () .build ("/ home/main", "ap") .route (this, 5); / / pass Bundle Bundle params = new Bundle () directly; ARouter.getInstance () .build ("/ home/main") .with (params) .request () / / specify Flag ARouter.getInstance () .build ("/ home/main") .withFlags (); .upload (); / feel that there are not enough interfaces, you can directly take out the Bundle assignment ARouter.getInstance () .build ("/ home/main") .getExtra (); / / use the green channel (skip all interceptors) ARouter.getInstance (). Build ("/ home/main"). GreenChannal (). Navigation ()

Gradle dependence

Dependencies {apt 'com.alibaba:arouter-compiler:1.0.1' compile' com.alibaba:arouter-api:1.0.2'} so much about how to build the Android page routing framework in Alibaba-ARouter. I hope the above content can be helpful to you and learn more. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report