References:

Superxlcr’s ARouter study notes

Code word migrant worker article

Prosperous fall as 666 articles

This article mainly introduces the knowledge points

  • The android routing framework solves the problem
  • Use of the Android Routing framework (ARouter is only introduced here)
  • A note about using the ARouter framework
  • conclusion

1. Problems solved by Android routing framework

I believe everyone will encounter such a problem in their work. When they jump to their designated App or page through other apps or web pages, they usually click in push or through Banner. The general operation is like the following

  • Set the corresponding intent-filter
<intent-filter>
	<action android:name="com.hejin.arouter.Main2Activity"/>
	<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
Copy the code
  • An implicit jump to an Activity with an Intent
	Intent intent = new Intent();
	intent.setAction("com.hejin.arouter.Main2Activity");
	startActivity(intent);
Copy the code

Actually here I want to explain, I think if you are a regular development company generally will not to write so, actually this jump can realize completely, but generally formal company will make some protocol and port number, that is to say, will add a scheme to specify the part of some data and path matching, but as time goes on and the team’s expansion, will be Slowly exposed a lot of problems:

  • Centralized URL management: Androidmanifest.xml is loaded with IntentFilter IntentFilter IntentFilter IntentFilter IntentFilter IntentFilter IntentFilter IntentFilter IntentFilter IntentFilter IntentFilter IntentFilter Multiple paths need to be solved frequently, such as overlapping paths, excessive activities exported, and security risks
  • Poor configurability: Manifest is limited to XML, cumbersome to write, complex to configure, and has few things to customize
  • No explicit dependencies across modules: In App small size, we will do to the App level, according to the business split into sub modules, completely decoupling between, through the packaging process control function of the App, so convenient to deal with big team collaboration, logic without interfering with each other, this time can only rely on implicit Intent to jump, write trouble, success is difficult to control.

Especially in the evolution of the project are modular development, so there are many online here a great god study way by the framework such a thing, to solve the corresponding problems of the above, here is contact alibaba open-source ARouter on making already have 3. Start the + k, it should be relatively stable, so let us Let’s go!

2. Simple use of ARouter

2.1 The first step was to introduce ARouter into the project

  • First configure the corresponding parameters in the Module
    defaultConfig {
        .......
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [ moduleName : project.getName() ]
            }
        }
    }
Copy the code
  • Then configure the API and compiler(this is also in the Module)
dependencies {
    compile 'com.alibaba:arouter-api:x.x.x'
    annotationProcessor 'com.alibaba:arouter-compiler:x.x.x'. }Copy the code
  • Github’s gradle project must add the following code:
    dependencies {
        classpath 'com. Android. Tools. Build: gradle: 2.3.3'
        classpath 'com. Neenbedankt. Gradle. Plugins: android - apt: 1.8'NOTE: Do not place your application dependencies here; they belong //in the individual module build.gradle files
    }
Copy the code

This sentence must add otherwise jump simply not past, specific why I return really do not know…. With the above content on the completion of the basic configuration, you can carry out the corresponding jump…

2.2 Simple use in code

  • Initialize ARouter in Application
/* Initialize the routing frame */ arouter.init (this);Copy the code
  • Start by adding comments to the Activity you want to jump to (or the target Activity)
@Route(path = "XXX/XXX")
Copy the code

Note two things here: first, the content of the annotation must be a secondary menu, which is explained on Github, and second, the annotation must be written on the Activity class

  • Jump through code (initiate routing)
ARouter.getInstance().build("/XXX/XXX").navigation(); Arouter.getinstance ().build()"/XXX/XXX")
             .withLong("key"."value")
             .withString("key"."value")
             .navigation
Copy the code

These parameters must be consistent with the parameters in the Activity annotation that you want to jump to. When you pass parameters, you simply retrieve them with the Intent.

The above steps can achieve the basic jump pass parameters, but as a strict programmer how can we be satisfied with this?

ARouter advanced use

3.1 Use Uri to Jump

        Uri uri = Uri.parse("/test/activity");
        ARouter.getInstance()
                .build(uri)
                .navigation();
Copy the code

3.2 The acquisition of transfer parameters

When you pass a parameter you can retrieve it with the Intent, or you can retrieve it with the Intent annotation, like the following:

@Autowired(name = "xxx")
public String text;
Copy the code

Notice here that the modifier must be public and the key values must correspond to each other. Also add **ARouter.getInstance().inject(this) to the target Activtiy; ** can use the corresponding value, otherwise the value will fail, but the null pointer is not reported.

3.3 Jump processing of transition animation

Have you ever thought, when the Activity before the jump can use overridePendingTransition (); But now with the route jump, there’s no place to get the Settings animation, and ARouter came up with this problem for us.

  • Before the old animation: use withTransition method (equivalent to the overridePendingTransition () method)
ARouter.getInstance().build(path).withTransition(R.anim_slide_in,R.anim_slide_out);
Copy the code
  • New animation: Use the withOptionsCompat method.
ActivityOptionsCompat compat = ActivityOptionsCompat.makeScaleUpAnimation(view, view.getWidth() / 2, view.getHeight() / 2, 0, 0);
ARouter.getInstance().build("path").withOptionsCompat(compat).navigation();
Copy the code

3.4 Result of ARouter processing the jump process

ARouter allows us to process the results of the jump. It’s what you do when you find your target.

ARouter.getInstance().build("/module/jumpTestActivity2").navigation(null,new NavigationCallback() {@override public void onFound(Postcard) {// How to do this} @override public void onLost(Postcard) {// Can't find target operation}});Copy the code

Note: There are already four methods in the latest API!

        ARouter.getInstance().build("/test/activity").navigation(this, new NavigationCallback() {@override public void onFound(Postcard) {// How to find the Postcard"done"."onFound: "); } @override public void onLost(Postcard) {"done"."onLost: ");
            }

            @Override
            public void onArrival(Postcard postcard) {
		//跳转成功
                Log.e("done"."onArrival: "); } @override public void onInterrupt(Postcard) {//"done"."onInterrupt: "); }});Copy the code

Here you can handle the results of “location page” jumps in onLost, such as upgrading the APP.

3.5 Activities that Carry results

ARouter.getInstance().build("/test/activity").navigation(this,10);
Copy the code

The last parameter is the request code, and everything else is the same.

3.6 Concepts of groups

There’s a group in ARouter. What does that mean? You can specify groups when building routing requests. Path =/test/activity test =/test/activity test =/test/activity test

@Route(path = "/test/activity", group = "app")
Copy the code

It is important to note that if you have a group set, you must use arouter.getInstance ().build(path, group) when jumping, otherwise you will not find the corresponding jump

3.7 Rewriting the Forward URL for redirection

Can redirect your URL address

@Route(path = "/test/activity2")
public class PathReplaceServerImp implements PathReplaceService {
    @Override
    public String forString(String path) {

        path = "/test/activity2";
        return path;
    }

    @Override
    public Uri forUri(Uri uri) {
        return null;
    }

    @Override
    public void init(Context context) {
        Log.e("done"."Init: Here's the method you execute when you initialize it."); }}Copy the code

Note: the above path must be annotated with an annotation that appears in any item, if the item does not appear, the null pointer exception will be reported. With the above code, you can change the path and URL for jump in your project.

3.8 ARouter interceptors

ARouter’s interceptors can intercept requests during navigation and perform a range of processing To implement an Interceptor, we first need to implement the IInterceptor interface, use the Interceptor annotation to mark our Interceptor, and pass in the priority parameter (the lower the number, the higher the priority) An interface to call back!

public class TestInterceotor implements IInterceptor {
    @Override
    public void process(Postcard postcard, final InterceptorCallback callback) {
        if (postcard.getPath().equals("/test/activity")) {
            callback.onContinue(postcard);
        } else {
            callback.onContinue(postcard);
        }
    }

    @Override
    public void init(Context context) {
        Log.e("done"."Init: Initial call"); }}Copy the code

Here are a few points:

  • First of all, the process method handles the interception, where I determine a corresponding annotation route and intercept it if it jumps to the corresponding path.
  • Secondly, callback.onContinue(postcard) Note that this sentence means that the postcard is handled by a route. If this sentence is not written here, the route will terminate.
  • The init method is executed globally only once. Forgive me for being a rookie
  • ** Interceptor(priority = 7)** Interceptor(priority = 7)** Interceptor(priority = 7)** Interceptor(priority = 7)** Interceptor(priority = 7)** Interceptor(priority = 7)** Interceptor(priority = 7)** Interceptor(priority = 7) The main thing is to get the interceptor passed down level by level. So you have multiple levels of interceptors.

The above content is just a simple use of the interceptor, but it is difficult to understand, after all, when directly said to let you achieve login interception, how you achieve, at the beginning I also feel simple, but when I write, I found that the problem is not so simple as it looks. Here I first put the content blocker code on, and then I explain!

  • Logic for the first jump
        ARouter.getInstance().build("/test/activity").navigation(this, new NavCallback() {
            @Override
            public void onArrival(Postcard postcard) {

            }

            @Override
            public void onInterrupt(Postcard postcard) {
                Log.e(TAG, "OnInterrupt: This method is executed after the interceptor executes"); }});Copy the code
  • Interceptor code:
@Interceptor(priority = 7) public class TestInterceotor implements IInterceptor { @Override public void process(Postcard  postcard, final InterceptorCallback callback) {if (postcard.getPath().equals("/test/activity")) {
            Log.e("done"."process: main2Activity");
            if(app.islogin) {/* Has logged in */ callback.onContinue(postcard); }else*/ arouter.getInstance ().build()"/test/activity2")
                        .withString("name", postcard.getPath()).navigation();
            }
            Log.e("done"."Process: complete");
        } else {
            Log.e("done"."Process: When is this method executed?");
            callback.onContinue(postcard);
        }
    }

    @Override
    public void init(Context context) {
        Log.e("done"."Init: Initial call"); }}Copy the code
  • Simulate the login Activity
@Route(path = "/test/activity2")
public class Main3Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        ARouter.getInstance().inject(this);
    }

    public void click(View view) {
        APP.isLogin = true;
        ARouter.getInstance().build("/test/activity").navigation(); finish(); }}Copy the code

Jump for the first time here, because the interceptor without landing logic can jump to the login page, I landed in simulated a landing page after the operation, then close the page, before I jump the target page again, this time due to have landed, so they will continue to perform a jump directly to the target page. This is pretty straightforward. There is a callback that I’m not sure what onInterrupt is going to do after that, but you can also pass in a field, and then pass in a field when you jump. This field basically holds the data of the page that you want to jump to, and then jump to. This solves the coupling problem.

3.9 Add additional parameters to interceptors

@Route(path = "/test/activity", extras = 0; /* Note that this is an int */)Copy the code

Note: This is an extra parameter added to the target’s Activity page, which will then take effect in the interceptor.

conclusion

In fact, THERE are still many problems about this framework that I do not understand, but I have already explained some basic contents. In fact, I got to know this framework mainly when I first saw the component-based development and saw this framework. In fact, I can also use it in the project and manage the jump overall. Write quite disorderly, thank you for your precious time to read, there is any wrong place hope correct.