Android APT 实现控件注入框架SqInject

背景

在游戏发行中,经常需要切包,如果直接使用R.id.xxx,在回编译时,由于resources.arsc会重新编译,R类中的id值和resources.arsc中的对应关系会异常,导致程序异常。我们有两种解决方法。

一种是在切包过程中纠正R类的值,实现方案具体介绍可以查看

游戏发行切包资源索引冲突解决方案,链接如下:

https://juejin.cn/post/6936058410655809550

另一种解决方案则是使用getIdentifier获取资源ID,放弃使用R类,这种方式中,编码较为麻烦,并且getIdentifier中需要写的是字符串,容易写错,并且编译过程中是发现不了的。基于这种情况,我们开发了基于getIdentifier的控件注入框架

一、APT技术简介

1、APT定义

APT(Annotation Processing Tool)即注解处理器,是一种处理注解的工具,确切的说它是javac的一个工具,它用来在编译时扫描和处理注解。注解处理器以Java代码作为输入,生成.java文件作为输出

2、注解定义

1、注解是一种能被添加到java代码中的元数据,类、方法、变量、参数和包都可以用注解修饰。

2、注解对于它所修饰的代码没有直接的影响

3、APT原理简介

Annotation processing是在编译阶段执行的,它的原理就是读入Java源代码,解析注解,然后生成新的Java代码。新生成的Java代码最后被编译成Java字节码,注解解析器(Annotation Processor)不能改变读入的Java 类,比如不能加入或删除Java方法

二、APT实战使用

1、SqInject框架来源

在手游发行中,经常需要切包,将游戏接完SDK1的包,通过反编译,替换smali文件及其他资源文件的方式,替换为渠道SDK2的渠道包。在这个反编译回编译的过程中,资源索引ID(即R类和resources.arsc中的ID映射关系)会发生冲突导致程序异常,即不做特殊处理的话,渠道SDK及发行SDK是不能直接使用R类的,要使用getIdentifier获取资源ID

要求在程序中使用getIdentifier,在开发过程中是比较麻烦的事情。在这样的条件下,我们也无法使用如butterknife这样的框架。因此,我们模仿butterknife开发了一套基于getIdentifier的控件注入框架SqInject。下面介绍SqInject的实现,先来看下简单使用

public class MainActivity extends AppCompatActivity {
  
    //绑定ID
    @BindView(SqR.id.tv)
    TextView hello;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SqInject.bind(this);
        Log.e("SqInject", hello.getText().toString());
    }


    //绑定点击事件
    @OnClick(SqR.id.tv)
    public void click(View view) {
        Intent intent = new Intent(MainActivity.this, TestActivity.class);
        startActivity(intent);
    }
}

2、SqInject的实现原理

2.1、注解处理器模块实现

上文说到APT常用于生成代码,在SqInject中APT注解处理环节中,流程如下图所示:

在编译过程中扫描注解,生成Java代码,而后再次编译

在SqInject代码中,实现如下:

@AutoService(Processor.class)
@SupportedSourceVersion(SourceVersion.RELEASE_7)
public class SqInjectProcessor extends AbstractProcessor {

    ...
	
    //核心方法
    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        //控件类注解解析,ResChecker检查资源id合法性,合法则生成"类名+$ViewBinder类,否则编译失败
        BindViewBuilder bindViewBuilder = new BindViewBuilder(roundEnvironment, mResChecker, mElementUtils, mTypeUtils, mFiler, mMessager);
        bindViewBuilder.build();
        //id类注解解析,ResChecker检查资源id合法性,合法则生成"类名+$IdBinder类",否则编译失败
        BindIdsBuilder bindIdsBuilder = new BindIdsBuilder(roundEnvironment, mResChecker, mElementUtils, mTypeUtils, mFiler, mMessager);
        bindIdsBuilder.build();
        return false;
    }
    
}
复制代码

在生成控件注入相关代码之前,框架中会先检测资源id的合法性,本框架中在使用注解时,传入的是字符串。可资源名称是有可能不存在对应资源的,框架会做相应的检测

2.2、资源检测

Android编译资源过程中,会生成R类,也就是说只有在R类中存在的,用getIdentifier才能够获取到,那么我们可以用R类来检测传入的参数是否合理,代码如下:

/**
     * 检测资源id在R文件中是否存在
     * @param name
     * @param type
     * @return
     */
    public boolean isIdValid(String name, String type) {
        String RClassName = mPackageNeme + ".R." + type;
        TypeElement RClassType = mElementUtils.getTypeElement(RClassName);
        if (RClassType == null) {
            mMessager.printMessage(Diagnostic.Kind.ERROR, RClassName + "不存在,请检查是否包名有误,或者类型错误");
        } else {
            //遍历属性
            for (Element element : RClassType.getEnclosedElements()) {
                String fieldName = element.getSimpleName().toString();
                if (name.equals(fieldName)) {
                    return true;
                }
            }
        }
        return false;
    }
复制代码
2.3、解析注解,生成代码

以解析BindView为例,代码如下:

/**
     * 解析BindView注解
     * @return
     */
    private Map<TypeElement, List<VariableElement>> parseBindView(){
        Set<Element> elements = (Set<Element>) mRoundEnvironment.getElementsAnnotatedWith(BindView.class);
        if (!Utils.isEmpty(elements)) {
            Map<TypeElement, List<VariableElement>> map = new HashMap<>();
            for (Element element : elements) {
                if (element instanceof VariableElement) {
                    //获取该属性所在类
                    TypeElement targetElement = (TypeElement) element.getEnclosingElement();
                    mTargetSet.add(targetElement);
                    if (map.get(targetElement) == null) {
                        List<VariableElement> targetStringLists = new ArrayList<>();
                        targetStringLists.add((VariableElement) element);
                        map.put(targetElement, targetStringLists);
                    } else {
                        map.get(targetElement).add((VariableElement) element);
                    }
                }
            }
            return map;
        }
        return null;
    }
复制代码

解析完BindView注解后,使用javapoet生成代码,篇幅有限,下面仅列出获取参数和生成代码的一小部分

if (mBindViewIdTargetMap != null && mBindViewIdTargetMap.get(targetElement) != null) {
                List<VariableElement> viewElements = mBindViewIdTargetMap.get(targetElement);
                //方法体
                for (VariableElement viewElement : viewElements) {
                    //获取属性名
                    String fieldName = viewElement.getSimpleName().toString();
                    //获取类型
                    TypeMirror typeMirror = viewElement.asType();
                    TypeElement fieldClassElement = (TypeElement) mTypeUtils.asElement(typeMirror);
                    mMessager.printMessage(Diagnostic.Kind.NOTE, "注解的字段类型为: " + fieldClassElement.getQualifiedName().toString());
                    TypeElement fieldType = mElementUtils.getTypeElement(fieldClassElement.getQualifiedName());
                    ClassName fieldClassName = ClassName.get(fieldType);
                    //获取@BindView注解的值,即名称
                    String name = viewElement.getAnnotation(BindView.class).value();
                    //检测名称是否合法
                    if(!mResChecker.isIdValid(name, "id")){
                        mMessager.printMessage(Diagnostic.Kind.ERROR, "R文件中不存在id为" + name + "的值");
                    }
                    methodBuilder.addStatement("target.$N = $T.findRequiredViewAsType(source, $S, $S, $T.class)", fieldName, JptConstants.UTILS, name, "field " + fieldName,fieldClassName);
                }
            }
复制代码

小小总结一下,在注解处理器中,最重要的两个环节,一个是解析注解,获取参数,然后是利用javapoet框架生成代码

下面看下生成的代码

public class MainActivity$ViewBinder implements ViewBinder<MainActivity> {
  @Override
  public void bindView(final MainActivity target, final View source) {
    //这里就是上面的代码生成的
    target.hello = ViewUtils.findRequiredViewAsType(source, "tv", "field hello", TextView.class);
    IdUtils.findViewByName("tv", source).setOnClickListener(new DebouncingOnClickListener() {
      public void doClick(View v) {
        target.click(v);
      }
    } );
  }
}
复制代码

到这里,就介绍完了使用APT生成代码了哈。本文中提到的框架SqInject是我们日常工作中会使用到的SqInject框架,该框架以开源,地址是: https://github.com/37sy/SqInject有兴趣的欢迎star哈

同时,在框架中,还有另一个很重要的环节,R类对应的SqR类,SqR类中记录的是项目中的资源对应的字符串名称,该模块是通过自定义gradle插件实现的,有兴趣可查看 https://juejin.cn/post/6877843974799753230

原文链接:https://juejin.cn/post/6936483330758017061

关注我获取更多知识或者投稿

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值