使用Kotlin编写6.0权限检查框架学习总结
很久之前就学习过编译时注解的原理,不过对于java的Element使用不多,这次又重新复习了一遍,顺便学习了一下使用kotlin来编写。
对于运行时注入和编译时注入,不知道的同学百度一下吧,其实不难理解,这里是主要是使用AbstractProcessor类在编译是自动生成类来避免一些使用反射的场景。要使用这个类首先需要一些预备知识。
Java 的Element
自动生成代码需要对这个接口做一定了解,大家可以参看这边文章,基本使用讲的比较详细了。
编译时注入项目结构
这里是app依赖permission-compiler,permission-compiler依赖permission-annotation。后面两个是java library,一定要是java的module,否则写注解处理器的时候有些类会找不到。接着首先修改build.gradle添加kotlin的库以及插件。
root
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.1.2-3'
ext.anko_version = '0.10.0'
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
app
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
//扩展插件,使用可以直接引用布局里view的id进行操作
apply plugin: 'kotlin-android-extensions'
//kotlin的apt 类似于java的apt
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.dn.tim.timcompiler"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile "org.jetbrains.anko:anko:$anko_version"
testCompile 'junit:junit:4.12'
compile project(':permission-annotation')
kapt project(':permission-compiler')
}
repositories {
mavenCentral()
mavenLocal()
}
permission-annotation
apply plugin: 'kotlin'
dependencies {
testCompile 'junit:junit:4.12'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
permission-compiler
apply plugin: 'kotlin'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.squareup:kotlinpoet:0.3.0'
compile project(':permission-annotation')
testCompile 'junit:junit:4.12'
}
主要是使用kotlin,配置gradle会稍微麻烦一点.
注解module
permission-annotation
这个module主要是定义了一些注解,为的是编译时能获取到对应的方法来生成代码。这里主要有三个注解
@Need表示需要获取请求的权限,OnDelined表示申请权限被拒绝,OnNeverAsk表示不再询问,三个注解都是一样接受一个参数。三个注解仅仅是名字有区别
package com.example
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
@Target