Preface: This article of modularization and componentization is introduced with 2 articles. Maybe some people think that there are already articles online, why do they need to write. First: in order to record their own normal also count as notes. Second: there are good articles on the Internet, but recently I saw an even more than 150 praise, but the introduction of the confused, a lot of knowledge points skipped. The focus of this article is to get you started, understand and use it quickly.

ARouter, or third-party routing frameworks, is the basic use of the ARouter routing framework. Android implements componentization through the management of Gradle. And with ARouter, arbitrary jump switch

Why is the routing framework used here? In order for modules to communicate with each other, for example, your project introduced Module A. Module B was also introduced. Projects can access both A and B. But what if A wants to access B, and B wants to access A. This is where the routing framework comes in. This is only one aspect.

1. Add dependencies

Add the dependencies of ARouter’s Github app build.gradle to the dependencies TAB

 implementation 'com. Alibaba: arouter - API: 1.3.1'
 annotationProcessor 'com. Alibaba: arouter - compiler: 1.1.4'
Copy the code

Add javaCompileOptions to defaultConfig under the Android TAB:

android {
    compileSdkVersion 28
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [moduleName: project.getName()]
            }
        }

    }
    
}
Copy the code


2. Initialize

To initialize the application, remember the release line version, to disable logging and debug, the code is as follows:

public class MyApplication extends Application {
    //ARouter Enables debugging
    private boolean isDebugARouter = true;

    @Override
    public void onCreate(a) {
        super.onCreate();
        context = this;
        if (isDebugARouter) {
            // The following 2 lines must be unmounted between ARouter init or invalid
            // Prints logs
            ARouter.openLog();
            // Enable debugging mode (must be enabled in InstantRun mode, must be disabled online)
            ARouter.openDebug();
        }

        // The official recommendation is to initialize it in Application
        ARouter.init(this);
    }

    @Override
    public void onTerminate(a) {
        super.onTerminate(); ARouter.getInstance().destroy(); }}Copy the code

While using ARouter is a bit like Dagger2, call ARouter.getInstance().inject(Object obj); We encapsulate it in Base:

public abstract class BaseActivity extends AppCompatActivity {
    // Omit some code for easy understanding
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentViewId());
        ARouter.getInstance().inject(this); }}Copy the code


3. Use of @route

In the Activity or Fragment we use. Use @route annotation and path = “/x/y”,x is the package name (take the last bit), y is the current class name:

@Route(path = "/myapplication/MainActivity")
public class MainActivity extends BaseActivity {}Copy the code


4, jump between activities in ARouter

An Activity and a jump in an Activity simply call the following code, the path in the build, which is marked with the @route path annotation:

ARouter.getInstance().build("/myapplication/MainActivity").navigation();
Copy the code

From the code above we can see that. / myapplication MainActivity “path”, have unified with a constant class management, otherwise this find, to simply, as follows:

public final class Constance {
    public static final String ACTIVITY_PATH_MAIN = "/myapplication/MainActivity";
}
Copy the code

In addition to the path jump, we can also see the Uri jump from its parameter type:

        Uri uri = Uri.parse(Constance.ACTIVITY_PATH_MAIN);
        ARouter.getInstance().build(uri).navigation();
Copy the code


5. Jump with parameters & get parameters

Jump with parameters

You just have.withString (), which contains all the types you want to pass

ARouter.getInstance()
                .build("/myapplication/MainActivity")
                .withString("name"."lihang")
                .withInt("age".27)
                .withSerializable("human".new Person("Force"."11"))
                .navigation();
Copy the code

To obtain parameters

On the Get Parameters page, notice the big hole:

@Route(path = "/myapplication/SimpleActivity")
public class SimpleActivity extends BaseActivity {
    @Autowired()
    String name;
    @Autowired(name = "age")
    int mAge;
    // @autowired (name = "human") @autowired (name = "human") Unless it is Paceable
    Person mPerson;

    @Override
    public int getContentViewId(a) {
        return R.layout.activity_simple;
    }

    @Override
    public void progressLogic(a) {
// mPerson = (Person) getIntent().getSerializableExtra("human");}}Copy the code

There are three ways to get parameters:

  • With the @Autowired annotation, the value below is the key that passes between values.
@Autowired()
String name;
Copy the code
  • With the @autowired annotation,name = key,name = key, whatever the parameter name is
@Autowired(name = "age")
int mAge;
Copy the code
  • Strip serialization is a little bit special here, if it’s a Parcelable type, you can get it above. But if it’s Serializable, you can’t get it. But it’s also available here with our traditional getIntent
mPerson = (Person) getIntent().getSerializableExtra("human");
Copy the code


6, drive the painting jump

Before we jump to drive the picture, to use the overridePendingTransition (int anim_in, int anim_out); It’s also available here, but there’s a big hole:

ARouter.getInstance()
                .build(Constance.ACTIVITY_PATH_SIMPLE)
                .withTransition(R.anim.alpha_activity_in, R.anim.alpha_activity_out)
                // Navigation must include the current Context otherwise the animation will not work
                .navigation(MainActivity.this.99);
Copy the code

ARouter also provides a new version of the animation, but requires API >= 16 to use, and the effect is still cool:

        if (Build.VERSION.SDK_INT >= 16) {
            ActivityOptionsCompat compat = ActivityOptionsCompat.
                    makeScaleUpAnimation(btn, btn.getWidth(), btn.getHeight(), 0.0);
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_PATH_SIMPLE)
                    .withOptionsCompat(compat)
                    .navigation();
        }else {
            ToastUtils.showToast("API <16, new animation not supported");
        }
Copy the code


StartActivityForResult (Intent Intent, int requestCode);

Take requestCode jump

Also in. Navigation (), just put the requestCode on it. The onActivityResult is then used as normal.

ARouter.getInstance()
                .build(Constance.ACTIVITY_PATH_SIMPLE)
                .navigation(Context context, int requestCode);
Copy the code

SetResult returns to the screen, you read that right, it’s that complicated!

Postcard postcard = ARouter.getInstance().build(Constance.ACTIVITY_PATH_MAIN); LogisticsCenter.completion(postcard); Class<? > destination = postcard.getDestination(); Intent intent =new Intent(SimpleActivity.this, destination);
        setResult(1, intent);
        finish();
Copy the code

8. Use of fragments

Both activities and fragments need the @route tag and the path tag. Fragment is used the same way as an Activity, but the only difference is that an Activity is a jump and a Fragment is an instance that instantiates Fragmen, as follows:

// Remember to push it, it is the same as Activity.
HomeFragment homeFragment = (HomeFragment)ARouter.getInstance().build(Constance.Fragment_PATH_SIMPLE).navigation();
Copy the code


9. Use of interceptors

Let’s start with a snippet of interceptor code:

@Interceptor(priority = 1)
public class FirstInterceptor implements IInterceptor {
    @Override
    public void process(Postcard postcard, InterceptorCallback callback) {
        if (postcard.getPath().equals(Constance.ACTIVITY_PATH_SIMPLE)){
            LogUtils.i("ARouter interceptor"."FirstInterceptor starts intercepting ======");
        }
        callback.onContinue(postcard);
    }
    @Override
    public void init(Context context) {
        LogUtils.i("ARouter interceptor"."first init"); }}Copy the code

1. Interceptors are very strange to use, as long as you write this class in your code, it will work. The @interceptor tag apt does a lot for us.

* Interceptor = @interceptor (priority = 1); the lower the priority is, the better it will be.

3, implement IInterceptor interface. Implement two methods: init () and process ().

4. The init () method is executed first when the project starts, and the process () method is called when the Activity jumps

5. If we want to add some optional conditions for the interceptor, it can be done through the Postcard

6. Note that as long as the interceptor is set up, callback.oncontinue (postcard) is not called here; It gets stuck in the current interceptor. Of course the jump is stuck on the current page.


10, jump when listening, with interceptor use

Go straight to the code. Comment in the code

        ARouter.getInstance()
                .build(Constance.ACTIVITY_PATH_SIMPLE)
                .navigation(MainActivity.this.new NavigationCallback() {
                    @Override
                    public void onFound(Postcard postcard) {
                        // Called when the route target is discovered (the Activity executes the jump code, the first one executes)
                        //group indicates the path group. If not, the default is x of path /x/y
                        // Group can be customized, for example: @route (path = constance.activity_path_main,group = constance.group_first)
                        // Of course, the group name should be added when jumping.
                        String group = postcard.getGroup();
                        // Path to @route (path = constance.activity_path_main)
                        String path = postcard.getPath();
                        LogUtils.i("ARouter interceptor"."onFound ------> group == " + group + "" + "path == " + path);
                    }

                    @Override
                    public void onArrival(Postcard postcard) {
                        // Call the route when it arrives (note that this is only called after all interceptors have executed)
                        String group = postcard.getGroup();
                        String path = postcard.getPath();
                        LogUtils.i("ARouter interceptor"."onArrival ------> group == " + group + "" + "path == " + path);
                    }

                    @Override
                    public void onLost(Postcard postcard) {
                        // Called when the route is lost
                        LogUtils.i("ARouter interceptor"."onLost");
                    }

                    @Override
                    public void onInterrupt(Postcard postcard) {
                        // Called when the route is intercepted
                        LogUtils.i("ARouter interceptor"."onInterrupt"); }});Copy the code

Conclusion: This is how ARouter is used. At present, I am studying crazily. Have like-minded or want to study with me, please add QQ group: 209010674. Also for next year to have better access to prepare. If it helps you, give me a thumbs up, give me a pat on the back.