Alibaba routing framework introduction

Android page jumps are usually done by directly specifying the component name with an intent, but when multiple modules are developed, this method will cause the coupling of each module to be serious, the code is too intrusive, and the purpose of complete separation of the modules cannot be achieved at this time. Need to use implicit intent to complete the page jump, that is, page routing. ARouter is an Android routing solution.

Simple to use

1. Add dependencies and configuration

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

dependencies {
    // 替换成最新版本, 需要注意的是api
    // 要与compiler匹配使用,均使用最新版可以保证兼容
    compile 'com.alibaba:arouter-api:x.x.x'
    annotationProcessor 'com.alibaba:arouter-compiler:x.x.x'
    ...
}
// 旧版本gradle插件(< 2.2),可以使用apt插件,配置方法见文末'其他#4'
// Kotlin配置参考文末'其他#5'

2. Add annotations

// 在支持路由的页面上添加注解(必选)
// 这里的路径需要注意的是至少需要有两级,/xx/xx
@Route(path = "/test/activity")
public class YourActivity extend Activity {
    ...
}

3. Initialize the SDK

if (isDebug()) {           // 这两行必须写在init之前,否则这些配置在init过程中将无效
    ARouter.openLog();     // 打印日志
    ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
}
ARouter.init(mApplication); // 尽可能早,推荐在Application中初始化

4. Initiate routing operation

// 1. 应用内简单的跳转(通过URL跳转在'进阶用法'中)
ARouter.getInstance().build("/test/activity").navigation();

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

Note that if you want to pass a custom object, you need to implement json serialization and deserialization:

@Route(path = "/service/json")
public class JsonServiceImpl implements SerializationService {
    @Override
    public void init(Context context) {

    }

    @Override
    public <T> T json2Object(String text, Class<T> clazz) {
        return JSON.parseObject(text, clazz);
    }

    @Override
    public String object2Json(Object instance) {
        return JSON.toJSONString(instance);
    }
}

URL Jump

ARouter's page jump also supports uri jump, as long as the path is correct, you can jump to the target interface, so we can also jump in the following way when jumping to the interface:

Uri uri = Uri.parse("arouter://m.aliyun.com/test/Main2Activity");
ARouter.getInstance().build(uri).navigation();

The scheme and host can be arbitrarily specified according to our needs.

The more important way to use it is when jumping from the web page to the APP:

// 新建一个Activity用于监听Schame事件,之后直接把url传递给ARouter即可
public class SchameFilterActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Uri uri = getIntent().getData();
    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>
</activity>

In this way, anyone who jumps from the webpage to the APP will pass the SchameFilterActivity filter, and then she will jump to the real Activity.

The webpage jump links are as follows:

<a href="router://m.aliyun.com/test/Main2Activity">跳转</a>

You can also add parameters behind the web page:

<a href="router://m.aliyun.com/test/Main2Activity?name=xuyu">跳转</a>

Then initialize the parameters by the following methods:

@Route(path = "/test/Main2Activity")
public class Main2Activity extends AppCompatActivity
{
    @Autowired
    String name;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        ARouter.getInstance().inject(this);
        Log.e("Main2Activity", name + "");

    }
}

Note that the parameters obtained in this way are passed parameters through the url, which are the parameters carried by the data, not directly carried by the intent. The original acquisition method is as follows:

getIntent().getData().getQueryParameter("name");

But the data obtained by the original way of ARouter jump will be empty. The jump uri can be obtained as follows:

getIntent().getStringExtra(ARouter.RAW_URI)

In fact, ARouter sends the string of uri to the next interface through the bundle.

Page blocking

First define an interceptor:

@Interceptor(priority = 8, name = "测试用拦截器")
public class TestInterceptor implements IInterceptor
{
    @Override
    public void process(Postcard postcard, InterceptorCallback callback)
    {
//        callback.onContinue(postcard);
        callback.onInterrupt(new RuntimeException("我觉得有点异常"));
    }

    @Override
    public void init(Context context)
    {

    }
}

Then specify the interceptor in the Activity:

@Route(path = "/test/SecondActivity",priority = 8)

In this way, when jumping to this Activity, it will be intercepted by the interceptor to decide whether to transfer to continue the jump:

ARouter.getInstance().build("/test/SecondActivity").navigation(FirstActivity.this, new NavigationCallback()
{

    @Override
    public void onInterrupt(Postcard postcard)
    {
        Log.e("FirstActivity", "onInterrupt" + (postcard != null ? postcard.toString() : "null"));
    }
});

You can also configure more additional information on the target page for the interceptor to process. For example, an interface may need to log in and bind a mobile phone number, you can write as follows:

//用二进制最低位判断是否登录,次高位判断是否绑定手机号
@Route(path = "/test/SecondActivity",priority = 8,extra=3)

Then judge in the interceptor:

//获取目标页面的extras,注意这里不可以使用postcard.getExtras()
//他是获取传到目标页面bundle信息的方法
int extra=postcard.getExtra()
if(((extra & 2) > 0) & ((extra & 1) > 0));
{
    //目标界面需要登录且绑定手机号
}
if((extra & 2) > 0)
{
    //目标界面仅需要绑定手机号(业务上不应该有这个状态)
}
if((extra & 1) > 0)
{
    //目标界面需要仅登录
}

Group management

ARouter manages the page routing path in groups. By default, the path we write is the group name, for example: the
@Route(path = "/test/SecondActivity")group name is test, which also explains why the previous path should be written at least two levels, because the group name is added For specific paths, a packet will only be initialized when a certain path in the packet is accessed for the first time.

It can also be grouped manually as follows:

@Route(path = "/test/1", group = "app")

After formulating the group, you must specify the group jump:

ARouter.getInstance().build("/test/1", "app").navigation();

ARouter does not recommend manually specifying groups.

Note: ARouter allows multiple groups in a module, but does not allow the same group in multiple modules, which will lead to conflicts in the mapping file.

Published 19 original articles · praised 8 · visits 4041

Guess you like

Origin blog.csdn.net/u014068277/article/details/81269474
Recommended