欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android路由框架-ARouter详解

程序员文章站 2023-02-15 15:55:16
文章大纲 一、页面路由基本介绍1.什么是页面路由2.为什么要使用页面路由二、页面路由框架ARouter介绍1.常用功能介绍2.常见应用场景三、源码下载四、参考文章 一、页面路由基本介绍 1.什么是页面路由 映射页面跳转关系,包含跳转相关的URL跳转及值传递、拦截器等功能。 2.为什么要使用页面路由 ......

文章大纲

一、页面路由基本介绍
1.什么是页面路由
2.为什么要使用页面路由
二、页面路由框架arouter介绍
1.常用功能介绍
2.常见应用场景
三、源码下载
四、参考文章

 
Android路由框架-ARouter详解

一、页面路由基本介绍

1.什么是页面路由

  映射页面跳转关系,包含跳转相关的url跳转及值传递、拦截器等功能。

2.为什么要使用页面路由

  在原始android开发中,当我们需要进行页面跳转时,正常写法如下:

intent intent = new intent(mcontext, xxactivity.class);
intent.putextra("key","value");
startactivity(intent);

intent intent = new intent(mcontext, xxactivity.class);
intent.putextra("key","value");
startactivityforresult(intent, 100);

上述写法容易出现以下问题:

  1. 多人协同开发的时候,大家都去androidmanifest.xml中定义各种intentfilter,使用隐式intent,最终发现androidmanifest.xml中充斥着各种schame,各种path,需要经常解决path重叠覆盖、过多的activity被导出,引发安全风险等问题
  2. 跳转过程中无法插手:直接通过intent的方式跳转,跳转过程开发者无法干预,一些面向切面的事情难以实施,比方说登录、埋点这种非常通用的逻辑,在每个子页面中判断又很不合理,毕竟activity已经实例化了
  3. 跨模块无法显式依赖:在app小有规模的时候,我们会对app做水平拆分,按照业务拆分成多个子模块,之间完全解耦,通过打包流程控制app功能,这样方便应对大团队多人协作,互相逻辑不干扰,这时候只能依赖隐式intent跳转,书写麻烦,成功与否难以控制

页面路由可以解决什么问题?

 
Android路由框架-ARouter详解

 

二、页面路由框架arouter介绍

1.常用功能介绍

应用内页面跳转

添加依赖

 
Android路由框架-ARouter详解

温馨提示:api 的版本和 compiler 的版本号需要用最新的。最新的版本在 github上可以找到。

重写application并初始化arouter

 
Android路由框架-ARouter详解
 
Android路由框架-ARouter详解

配置将要跳转的页面

 
Android路由框架-ARouter详解

进行简单的页面跳转

 

 
Android路由框架-ARouter详解

温馨提示:如果你想实现像 startactivityforresult() 功能,可以这样使用

 
Android路由框架-ARouter详解

运行结果如下:

 
Android路由框架-ARouter详解
 
Android路由框架-ARouter详解

携带参数进行页面跳转

 
Android路由框架-ARouter详解

温馨提示:支持数据类型如下:

//基础类型
.withstring( string key, string value )
.withboolean( string key, boolean value)
.withchar( string key, char value )
.withshort( string key, short value)
.withint( string key, int value)
.withlong( string key, long value)
.withdouble( string key, double value)
.withbyte( string key, byte value)
.withfloat( string key, float value)
.withcharsequence( string key,  charsequence value)

//数组类型
.withparcelablearraylist( string key, arraylist<? extends parcelable > value)
.withstringarraylist( string key,  arraylist<string> value)
.withintegerarraylist( string key, arraylist<integer> value)
.withsparseparcelablearray( string key, sparsearray<? extends parcelable> value)
.withcharsequencearraylist( string key, arraylist<charsequence> value)
.withshortarray( string key,  short[] value)
.withchararray( string key, char[] value)
.withfloatarray( string key, float[] value)
.withcharsequencearray( string key,  charsequence[] value)

//bundle 类型
.with( bundle bundle )

//activity 跳转动画
.withtransition(int enteranim, int exitanim)

//其他类型
.withparcelable( string key, parcelable value)
.withparcelablearray( string key,  parcelable[] value)
.withserializable( string key, serializable value)
.withbytearray( string key, byte[] value)
.withtransition(int enteranim, int exitanim)
 
Android路由框架-ARouter详解

运行程序,结果如下图所示:

 
Android路由框架-ARouter详解
 
Android路由框架-ARouter详解

路由监听
在路由跳转的过程中,我们可以监听路由的过程,只需要以下使用:

navigation(context context, navigationcallback callback)

navigationcallback 的源码如下:

public interface navigationcallback {

    /**
     * callback when find the destination.
     * 找到了
     * @param postcard meta
     */
    void onfound(postcard postcard);

    /**
     * callback after lose your way.
     * 找不到了
     * @param postcard meta
     */
    void onlost(postcard postcard);

    /**
     * callback after navigation.
     * 跳转完了
     * @param postcard meta
     */
    void onarrival(postcard postcard);

    /**
     * callback on interrupt.
     * 被拦截了
     * @param postcard meta
     */
    void oninterrupt(postcard postcard);
}

添加用于测试跳转的页面

 
Android路由框架-ARouter详解
 
Android路由框架-ARouter详解

在跳转的页面中添加监听代码

 
Android路由框架-ARouter详解

运行结果如下:

 
Android路由框架-ARouter详解
 
Android路由框架-ARouter详解
 
Android路由框架-ARouter详解

拦截器使用
添加需要跳转的页面

 
Android路由框架-ARouter详解

添加拦截器

 
Android路由框架-ARouter详解

在主页面进行跳转拦截测试

 
Android路由框架-ARouter详解

路由分组
在前面我们讲到在对 activity1 做注解的时候,用到了

@route(path = "/com/activity1")
public class activity1 extends appcompatactivity {}

  在 path 这个字符串里面,”com” 就代表组的标识;“activity1” 代表是 activity1 类的具体表示。组的标识和类的标识都可以自己定义的,需要记住的是组标识和类标识之间用斜杠来区分 ”\” .

什么是组?
  这里就需要提下,arouter框架是分组管理,按需加载。提起来很高深的样子呢!其实解释起来就是,在编译期框架扫描了所有的注册页面/服务/字段/拦截器等,那么很明显运行期不可能一股脑全部加载进来,这样就太不和谐了。所以就分组来管理,arouter在初始化的时候只会一次性地加载所有的root结点,而不会加载任何一个group结点,这样就会极大地降低初始化时加载结点的数量。比如某些activity分成一组,组名就叫test,然后在第一次需要加载组内的某个页面时再将test这个组加载进来。

测试一下:

arouter.getinstance()
       .build("/wxc/activity1")
       .navigation(this, new navcallback() {
            @override
            public void onarrival(postcard postcard) {
                string group = postcard.getgroup();
                log.e("zhao", "分组是: " + group);
            }
        });

结果是

07-27 17:32:17.880 19449-19449/com.router e/zhao: 分组是: wxc

arouter 默认情况下的分组就是第一个 / / 之间的内容。

自定义分组
  创建 customgroupactivity 并且添加 注解,并且指定路由分组。自定义分组的就是在原来的注解上添加 group 字段, 如下所示。

@route(path = "/com/customgroupactivity" , group = "customgroup")
public class customgroupactivity extends appcompatactivity {

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_custom_group);
    }
}

自定义分组,发起路由:第二个参数就是路由的分组

build(string path, string group)

具体实现如下所示:

 arouter.getinstance().build("/com/customgroupactivity", "customgroup").navigation();

url 跳转
web url 跳转流程图

 
Android路由框架-ARouter详解

创建url 中间跳转页
创建 urlreceiveactivity

/**
 * url 中转activity
 */
public class urlreceiveactivity extends appcompatactivity {

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);

        setcontentview( r.layout.activity_url_receive );

        //对uri 数据分发
        uri uri = getintent().getdata();
        arouter.getinstance().build(uri).navigation(this, new navcallback() {
            @override
            public void onarrival(postcard postcard) {
                finish();
            }
        });
    }
}

urlreceiveactivity 添加注册

<activity android:name=".urlreceiveactivity">
      <!-- schame -->
      <intent-filter>
            <data
                android:host="zhaoyanjun"
                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>

这里面的 host 、scheme 字段很重要。点击 url 会根据这两个字段会调起本地的 activity 。

下面是一段 html 片段

<h2>1:url普通跳转</h2>

<p><a href="arouter://zhaoyanjun/com/urlactivity1">arouter://zhaoyanjun/com/urlactivity1 </a>
</p>

<h2>2:url普通跳转携带参数</h2>

<p>
<a href="arouter://zhaoyanjun/com/urlactivity2?name=alex&age=18&boy=true&high=180&obj=%7b%22name%22%3a%22jack%22%2c%22id%22%3a666%7d">arouter://zhaoyanjun/test/urlactivity2?name=alex&age=18&boy=true&high=180&obj={"name":"jack","id":"666"}
</a>
</p>

注意 a 标签里面的  分别代表着 scheme 、host ;/com/urlactivity1 就是目标 activity 的注解。

如果需要接收 url 中的参数,需要在 activity 调用自动注入初始化方法;

arouter.getinstance().inject(this);

需要注意的是,如果不使用自动注入,那么可以不写 arouter.getinstance().inject(this),但是需要取值的字段仍然需要标上 @autowired 注解,因为 只有标上注解之后,arouter才能知道以哪一种数据类型提取url中的参数并放入intent中,这样您才能在intent中获取到对应的参数

具体的代码如下:

@route(path = "/com/urlactivity2")
public class urlactivity2 extends appcompatactivity{

    private textview textview;

    @autowired
    string name;

    @autowired
    int age;

    @autowired
    boolean boy;

    @autowired
    int high;

    @autowired
    string obj ;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        arouter.getinstance().inject(this);
        setcontentview(r.layout.activity_url2);

        textview = (textview) findviewbyid(r.id.tv);

        //解析参数
        bundle bundle = getintent().getextras();
        string name1 = bundle.getstring("name");

        textview.settext("参数是: " + "name: " + name + "  age: " + age
                + " boy: " + boy + " name1: " + name1 + " obj: " + obj.tostring() );
    }
}

效果图如下:

 
Android路由框架-ARouter详解

暴露服务
  这里说到的服务不是android四大组件中的service,这里的服务是接口开发的概念,就是将一部分功能和组件封装起来成为接口,以接口的形式对外提供能力,所以在这部分就可以将每个功能作为一个服务,而服务的实现就是具体的业务功能。

我们先自定义一个接口 iservice 并且继承 iprovider 。iservice 接口里面有一个 sayhello() 方法,具体代码如下。

public interface iservice extends iprovider {
    void sayhello(context context );
}

先定义一个 iservice 的实现类 myservice 并且添加注解,代码如下

@route(path = "/service/hello", name = "测试服务")
public class myservice implements iservice {

    @override
    public void sayhello( context context ) {
        toast.maketext(  context , "hello", toast.length_short).show();
    }

    @override
    public void init(context context) {

    }
}

发现服务,首先定义服务对象,并且添加注解,我们不需要知道接口的具体实现类。

@autowired(name = "/service/hello")
iservice service;

然后添加注解初始化,自动赋值。

arouter.getinstance().inject(this);

最后我们调用 service 里面的 sayhello() 方法。

service.sayhello(this);

发现服务这个功能的特点在于,我们只需要知道接口,不需要关心接口的实现类,很好了实现了解耦。

路由关闭

arouter.getinstance().destroy();

温馨提示:该功能慎用,搞不好整个app页面跳转就gg了。

代码混淆
  如果我们使用了proguard进行代码混淆,可以添加以下代码

-keep public class com.alibaba.android.arouter.routes.**{*;}
-keep class * implements com.alibaba.android.arouter.facade.template.isyringe{*;}

2.常见应用场景

  1. 从外部url映射到内部页面,以及参数传递与解析
    说明:该场景使用到了该文章的url跳转和暴露服务功能,这样使得页面跳转功能很好的解耦,特别对于团队开发有很好管理作用。
  2. 跨模块页面跳转,模块间解耦
  3. 处理登陆、埋点等逻辑
    说明:该场景使用到了路由监听和拦截跳转等功能,在原始处理登陆、埋点等功能中,我们会先初始化activity,再进行逻辑判断,这样会影响性能,如果我们使用了监听和拦截,那么在初始化新的activity之前,我们可以先进行逻辑判断。

三、源码下载

链接:https://pan.baidu.com/s/1y7br3ikldb-55vg1kau70a
提取码:m0at

四、参考文章