组件化基础ARouter(三、参数传递与解析)_arouter传参-程序员宅基地

技术标签: 组件化基础ARouter  android  

一、ARouter概述

  ARouter是一个用于帮助Android App进行组件化改造的框架 —— 支持模块间的路由、通信、解耦。ARouter的典型应用场景有:

  1. 从外部URL映射到内部页面,以及参数传递与解析;
  2. 跨模块页面跳转,模块间解耦;
  3. 拦截跳转过程,处理登陆、埋点等逻辑;
  4. 跨模块API调用,通过控制反转来做组件解耦;
      本篇主要介绍ARouter的用法之一:参数传递与解析。

二、基础用法

  仍然和"组件化基础ARouter(一)"中举相同的例子:在MainActivity中有一个FirstButton,FirstButton点击后打开模块first_library中的FirstActivity,不同的是,这次在打开FirstActivity时需要传递一个int参数(10)、String参数(“hello”)、User参数:

  在不使用ARouter的情况下,简单的实现方式是通过intent传递:

public class MainActivity extends Activity implements View.OnClickListener {
    
    @Override
    public void onClick(View v) {
    
        if (v.getId() == R.id.main_button) {
    
            User user = new User("jack", 18);
            Intent intent = new Intent(this, FirstActivity.class);
            // 1.往intent中添加参数
            intent.putExtra("intValue", 10);
            intent.putExtra("strValue", "hello");
            intent.putExtra("user", user);
            startActivity(intent);
        }
    }
}

public class FirstActivity extends AppCompatActivity implements View.OnClickListener {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        // ...省略部分代码
        // 2.从intent中取参数
        Intent intent = getIntent();
        intValue = intent.getIntExtra("intValue", 0);
        strValue = intent.getStringExtra("strValue");
        user = intent.getParcelableExtra("user");
        firstIntTextView.setText("intValue:"+intValue);
        firstStrTextView.setText("strValue"+strValue);
        firstUserTextView.setText("User:"+user.name+":"+user.age);
    }
}

  下面介绍ARouter参数传递的方式:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
    @Override
    public void onClick(View v) {
    
        if (v.getId() == R.id.main_button) {
    
            User user = new User("jack", 18);
            // 1.通过with系列方法传递对应类型参:支持基础类型及Parcelable、Serializable对象
            ARouter.getInstance().build("/first/activity")
                    .withInt("intValue", 10)
                    .withString("strValue", "hello")
                    .withParcelable("user", user)
                    .navigation();
        }
    }
}

@Route(path = "/first/activity")
public class FirstActivity extends AppCompatActivity implements View.OnClickListener {
    

    // 2.需要由ARouter传递的参数需要加@Autowired注解
    @Autowired
    public int intValue;
    @Autowired
    public String strValue;
    @Autowired
    public User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        // 3.ARouter.getInstance().inject(this)方法会自动完成参数注入
        ARouter.getInstance().inject(this);
        firstIntTextView.setText("intValue:"+intValue);
        firstStrTextView.setText("strValue"+strValue);
        firstUserTextView.setText("User:"+user.name+":"+user.age);
    }
}

  上面例子中的User必须是Parcelable对象,另外ARouter的withObject()方法可以直接传递非Parcelable对象,不过需要自己实现SerializationService接口来实现序列化方式,使用较少,这里不多介绍。

  至此,介绍了参数传递与解析的两种实现。下面分析源码实现。

三、源码分析

  下面通过源码来分析ARouter是如何实现第二节中的功能的。本文例子比"组件化基础ARouter(一)"中新增的API是:

  1. @Autowired注解;
  2. withParcelable()方法;
  3. inject()方法;
    相应地,本节分三小节来分析每步的主要工作。

3.1 @Autowired注解

  在2.2中在需要由ARouter注入的参数上添加@Autowired添加注解后,ARouter是使用2.1小节中声明的arouter-compiler来处理注解,自动生成代码,在此基础上实现参数传递的功能。关于Annotation Processor的基知识可参考:Annotation Processor简单用法

  ARouter APT处理@Autowired后自动生成一个class文件(位于/first_library/build/generated/source/kapt/debug/com/bc/first目录下):

  这个class实现了ISyringe,位于com.bc.first包下(与@Autowired标记参数的所在类的包名一样):

/**
 * DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY AROUTER. */
public class FirstActivity$$ARouter$$Autowired implements ISyringe {
    
  private SerializationService serializationService;

  @Override
  public void inject(Object target) {
    
    serializationService = ARouter.getInstance().navigation(SerializationService.class);
    FirstActivity substitute = (FirstActivity)target;
    substitute.intValue = substitute.getIntent().getIntExtra("intValue", substitute.intValue);
    substitute.strValue = substitute.getIntent().getExtras() == null ? substitute.strValue : substitute.getIntent().getExtras().getString("strValue", substitute.strValue);
    substitute.user = substitute.getIntent().getParcelableExtra("user");
  }
}

  后面再分析自动生成的代码有什么用途。

3.2 Postcard.withParcelable()

  在"组件化基础ARouter(一)"中分析过ARouter.getInstance().build(“/first/activity”)会返回PostCard对象,接着分析PostCard.withParcelable()的主要工作:

public final class Postcard extends RouteMeta {
    
    private Bundle mBundle;
    
    public Postcard withInt(@Nullable String key, int value) {
    
        mBundle.putInt(key, value);
        return this;
    }
    public Postcard withParcelable(@Nullable String key, @Nullable Parcelable value) {
    
        mBundle.putParcelable(key, value);
        return this;
    }
}

  上面的工作内容很简单:将需要传递的对象赋值到Postcard的Bundle中,接下来在navigation()的中就会将PostCard中的Bundle放到Intent来启动Activity(启动Activity的完整流程见"组件化基础ARouter(一)"):

final class _ARouter {
    
    private Object _navigation(final Postcard postcard, final int requestCode, final NavigationCallback callback) {
    
        final Context currentContext = postcard.getContext();
        switch (postcard.getType()) {
    
            case ACTIVITY:
                final Intent intent = new Intent(currentContext, postcard.getDestination());
                // 重点代码
                intent.putExtras(postcard.getExtras());
                String action = postcard.getAction();
                if (!TextUtils.isEmpty(action)) {
    
                    intent.setAction(action);
                }
                runInMainThread(new Runnable() {
    
                    @Override
                    public void run() {
    
                        // 3.启动Activity
                        startActivity(requestCode, currentContext, intent, postcard, callback);
                    }
                });
                break;
        }
        return null;
    }
}

3.3 inject()

  接着分析ARouter.getInstance().inject(this);的主要工作:

final class _ARouter {
    
    static void inject(Object thiz) {
    
        // 获取AutowiredService服务的实例对象
        AutowiredService autowiredService = ((AutowiredService) ARouter.getInstance().build("/arouter/service/autowired").navigation());
        if (null != autowiredService) {
    
            autowiredService.autowire(thiz);
        }
    }
}

  以上代码分析出:具体工作是由AutowiredService完成的。

3.3.1 AutowiredService

  AutowiredService接口继承了IProvider接口,ARouter的IProvider可理解为服务提供者(详见"组件化基础ARouter(二)"中的分析):

public interface AutowiredService extends IProvider {
    
    /**
     * Autowired core.
     * @param instance the instance who need autowired.
     */
    void autowire(Object instance);
}

3.3.2 AutowiredServiceImpl

  AutowiredService的实现是AutowiredServiceImpl,接着分析其autowire()方法:

@Route(path = "/arouter/service/autowired")
public class AutowiredServiceImpl implements AutowiredService {
    
    // LruCache存放着ISyringe对象
    private LruCache<String, ISyringe> classCache;
    private List<String> blackList;

    @Override
    public void init(Context context) {
    
        classCache = new LruCache<>(50);
        blackList = new ArrayList<>();
    }

    @Override
    public void autowire(Object instance) {
    
        doInject(instance, null);
    }

    /**
     * 递归注入参数
     */
    private void doInject(Object instance, Class<?> parent) {
    
        Class<?> clazz = null == parent ? instance.getClass() : parent;
        ISyringe syringe = getSyringe(clazz);
        if (null != syringe) {
    
            // 由syringe完成注入
            syringe.inject(instance);
        }
        Class<?> superClazz = clazz.getSuperclass();
        // 递归注入
        if (null != superClazz && !superClazz.getName().startsWith("android")) {
    
            doInject(instance, superClazz);
        }
    }
    /**
     * 获得等待注入的类的注入器类
     * 本文例子中,等待注入的类是FirstActivity,注入器类是FirstActivity$$ARouter$$Autowired
     */
    private ISyringe getSyringe(Class<?> clazz) {
    
        String className = clazz.getName();
        try {
    
            if (!blackList.contains(className)) {
    
                // 1.LruCache中是否有对应的注入器类实力
                ISyringe syringeHelper = classCache.get(className);
                if (null == syringeHelper) {
    
                    // 2.LruCache中没有,则根据ClassName+SUFFIX_AUTOWIRED构造一个
                    syringeHelper = (ISyringe) Class.forName(clazz.getName() + SUFFIX_AUTOWIRED).getConstructor().newInstance();
                }
                // 3.更新LruCache,然后返回注入器类
                classCache.put(className, syringeHelper);
                return syringeHelper;
            }
        } catch (Exception e) {
    
            blackList.add(className);    // This instance need not autowired.
        }
        return null;
    }
}

  上述代码中,注入器类的查找是根据ClassName + SUFFIX_AUTOWIRED查找的,后缀固定为’$ A R o u t e r ARouter ARouter$Autowired’,这样就与3.1中介绍的自动生成的类关联了起来。

3.3.4 ISyringe

  Syringe指注射器,结合3.1小节分析@Autowired注解自动生成的代码,内容就比较简单:

/**
 * DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY AROUTER. */
public class FirstActivity$$ARouter$$Autowired implements ISyringe {
    
  private SerializationService serializationService;

  @Override
  public void inject(Object target) {
    
    // 1.是否有自定义的序列化实现,默认为null
    serializationService = ARouter.getInstance().navigation(SerializationService.class);
    // 2.获得要注入的类
    FirstActivity substitute = (FirstActivity)target;
    // 3.注入的实现,其实也是从intent中取出来的
    substitute.intValue = substitute.getIntent().getIntExtra("intValue", substitute.intValue);
    substitute.strValue = substitute.getIntent().getExtras() == null ? substitute.strValue : substitute.getIntent().getExtras().getString("strValue", substitute.strValue);
    substitute.user = substitute.getIntent().getParcelableExtra("user");
  }
}

3.4 总结

  1. Arouter通过ARouter.getInstance().inject(this);实现控制反转;
  2. Arouter通过APT处理@Autowired注解来自动生成注入的代码;
  3. Arouter通过ARouter.getInstance().build(“/first/activity”).withParcelable(“user”, user) .navigation();来传递参数,实现方式是将数据放到Postcard中,在Postcard.navigation()打开Activity时将参数放到intent中;
  4. Arouter在ARouter.getInstance().inject(this)方法中会调用APT自动生成的代码将参数从intent中取出赋给对应变量;
  5. 控制反转的主要工作是ARouter内的AutowiredService来完成的;

The End

欢迎关注我,一起解锁更多技能:BC的掘金主页~ BC的CSDN主页
请添加图片描述

ARouter官方文档:https://github.com/alibaba/ARouter/blob/master/README_CN.md

组件化ARouter系列(一、启动Activity):https://juejin.cn/post/7048527567346728990/

组件化ARouter系列(二、跨模块API调用):https://juejin.cn/post/7053399480191680520/

组件化ARouter系列(三、参数传递与解析):https://juejin.cn/post/7053405921065566244/

组件化ARouter系列(四、拦截器):https://juejin.cn/post/7053749555892289572/

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_55626853/article/details/123929580

智能推荐

计算距离方法总结_两条线之间的欧式距离怎么算-程序员宅基地

文章浏览阅读2.5k次。欧氏距离(Euclidean Distance)欧式距离是最经典的一种距离算法,适用于求解两点之间直线的距离,适用于各个向量标准统一的情况,如各种药品的使用量、商品的售销量等。 欧氏距离也是最易于理解的一种距离计算方法,源自欧氏空间中两点间的距离公式。 二维空间上两点a(x1,y1)a(x_1,y_1)与b(x2,y2)b(x_2,y_2)之间的欧式距离: d12=(x1−x2)2+(y1−y_两条线之间的欧式距离怎么算

数学建模常用软件_什么软件可以分析数学建模的问题,以及给出合理的解释和分析-程序员宅基地

文章浏览阅读3.9w次,点赞78次,收藏436次。我参加过的数学建模比赛很多,除了本校的两次数学建模(二三等)外,全国数学建模(省二),亚太数学建模(s),ICM/MCM(M),五一建模联赛,电工杯(最近正在准备),之前错过mathorcup,有点遗憾。到2019年暑假前,总计自己一年左右参加7次建模比赛,说下自己建模常用的软件使用,本人在队里主要负责编程,但是写作和建模也同样会和队友交流。论文类LaTeX与WordWor..._什么软件可以分析数学建模的问题,以及给出合理的解释和分析

计算机网络原理知识_throught up速率-程序员宅基地

文章浏览阅读3k次。计算机网络原理╭第一章 计算机网络概述|第二章 网络应用|第三章 传输层|第四章 网络层内容大纲<|第五章 数据链路层与局域网|第六章 物理层|第七章 无线与移动网络╰第八章 网络安全基础第一章 计算机网络概述1.计算机网络基本概念(填空选择题)1>计算机网络定义*1.定义:1)计算机网络是 互连的、自治的 计算机的集合;互连: 是指利用通信链路链接相互独立的计算机系统;自治: 是指互连的计算机系统 彼此独立 ,不存在主从或控制与被控制的关系;2)一个计算机网络_throught up速率

html标签之视频各种标签_html 实现视频详情多tag标签-程序员宅基地

文章浏览阅读1.4k次。html标签之Object标签详解的定义和用法定义一个嵌入的对象。请使用此元素向您的 XHTML 页面添加多媒体。此元素允许您规定插入 HTML 文档中的对象的数据和参数,以及可用来显示和操作数据的代码。 标签用于包含对象,比如图像、音频、视频、Java applets、ActiveX、PDF 以及 Flash。object 的初衷是取代 img 和 applet 元素。不_html 实现视频详情多tag标签

(3)组合数学--鸽巢原理之最简单形式_鸽巢原理的三个公式-程序员宅基地

文章浏览阅读220次。定理:把n+1个物体放进n个盒子中,至少有一个盒子中含有两个物体理解:ai为第i天下的总棋盘数,显然an为递增序列,对an做部分和序列:如上图所示,上面77项,下面77项,共154项,153个盒子,所有存在aj+21 = ai,所以21 = aj - ai = bi + bi+1 + … + bj相当于19个物体,18个盒子五个点,四个三角形反证:Li <..._鸽巢原理的三个公式

Qt开发笔记之QCustomPlot:QCustomPlot介绍、编译与使用_qcustomplot编译-程序员宅基地

文章浏览阅读6.6w次,点赞20次,收藏194次。欢迎技术交流和帮助,提供所有IT相关的服务,有需要请联系博主QQ: 21497936,若该文为原创文章,未经允许不得转载原博主博客地址:http://blog.csdn.net/qq21497936本文章博客地址:http://blog.csdn.net/qq21497936/article/details/77847820目录效果 ​Demo下载地址QCustom..._qcustomplot编译

随便推点

教你玩Robocode(3) —— 坦克基础知识_robocode炮和机身的运动分离-程序员宅基地

文章浏览阅读4.4k次。在Robocode中,坦克分为3个部件: 身体(Body)、炮塔(Gun)、雷达(Radar)。 因此,在Robot类(还记得吗,它是任何坦克的父类)中,有对这些部件操作的方法。要查看Robocode提供的API,可以在robocode目录下的javadoc下找到,也可以在Robocode程序的帮助菜单中找到: 对于Body来说,Robot类提供了4个方法:_robocode炮和机身的运动分离

The number of divisors(约数) about Humble Numbers hdu 1492-程序员宅基地

文章浏览阅读77次。Problem DescriptionA number whose only prime factors are 2,3,5 or 7 is called a humble number. The sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, ... shows the first...

程序员成长记录(前端转后端)-程序员宅基地

文章浏览阅读6.6k次,点赞6次,收藏5次。一位大学毕业生第一份工作不太满意,裸辞跳槽的故事_前端转后端

深度优先算法(DFS)的python实现及骑士周游问题解析_用python代码写深度优先遍历算法的时间复杂度-程序员宅基地

文章浏览阅读3.2k次,点赞3次,收藏21次。背景: 骑士周游问题在棋盘格里,马走日,遍历所有网格点,找到每个网格都走过,且只有一次的路径。算法实现:用于解决骑士周游问题的图搜索算法是深度优先搜索(DFS),该算法是逐层建立搜索树,沿着树的单支尽量深入的向下搜索。连接尽量多的顶点,必要时可以进行分支。深度优先搜索同样要用到顶点的“前驱”属性,来构建树或森林。另外需要设置“发现时间”和“结束时间”属性。发现时间是在第几步访问到了这个顶点(设置灰色);结束时间是在第几步完成了此顶点的探索(设置黑色)。通用的深度优先搜索算法代码:# BFS采_用python代码写深度优先遍历算法的时间复杂度

PHP4用户手册:函数->fwrite (转)-程序员宅基地

文章浏览阅读53次。PHP4用户手册:函数->fwrite (转)[@more@]fwrite(PHP 3, PHP 4 >= 4.0.0)fwrite--二进制文件写入 描述int fwrite (int fp, ..._php fwrite int 4

0 0/1 * * * ?-程序员宅基地

文章浏览阅读4.7w次,点赞6次,收藏27次。定时任务<property name="cronExpression"> <value>0 0/1 * * * ?</value><!-- [秒] [分] [时] [日] [月] [星期][年] -->年可有可不有,星期一般都写?,你可以指定第几周星期几 1#1,或者从周一到周日1/7或者本月最后一个星期一,1L,..._0 0/1 * * * ?