Reason
First explain why there is this article. Previous time, plug-in and hot repair technology is very hot, Nuwa hot Repair Tool Nuwagradle, Ctrip dynamic Loading technology dynamicapk, there is hope to do the most lightweight plug-in framework of small. One common place for these three apps is the massive use of Gradle, a powerful build tool that, in addition to the Ctrip framework, has released a standalone Gradle plugin that provides an automated build plugin or a hot fix patch. So it is a very meaningful thing to learn about the Gradle plugin writing.
Plug-in type
Gradle plug-ins generally have such a few:
- One is written directly in the Gradle file in the project, the disadvantage of which is the inability to reuse the plug-in code, in other projects also have to copy the code (or to say that the file is copied again)
- The other is to write the plug-in in a separate project, and then publish it to the central warehouse, then direct reference to it, the advantage is reusable. Just like the Nuwa and small above.
Gradle related syntax
This article will not elaborate on gradle related syntax, if you want to learn gradle related things, please see gradle for Android
Gradle Plug-in development
Gradle plugins are developed using groovy, and groovy is actually compatible with Java. Android Studio In addition to the development of Android app, fully qualified to develop Gradle plug-in this work, the following talk about how to develop specific.
- First, create a new Android project.
- After that, create a new Android module project, type select Android Library.
- Delete all the remaining files in the new module except for the Build.gradle file, and then delete all the contents of the Build.gradle file.
- Create a new folder in the new module SRC, and then in the src file directory under the new main folder, in the main directory under the new groovy directory, the Groovy folder will be recognized by Android as the groovy source directory. In addition to creating a new groovy directory under the main directory, you will also create a new resources directory under the main directory, which is automatically recognized as a resource folder. Create a new project package name in the Groovy directory, just like the Java package name. Under the Resources directory, create a new Gradle-plugins folder under the new Folder Meta-inf,meta-inf folder. This completes the Gradle plug-in project's overall construction, followed by small details. Currently, the structure of the project is this way.
Open the Build.gradle file under module, enter
‘groovy‘‘maven‘{ compile gradleApi() compile localGroovy()}{ mavenCentral()}
Next we create a new file under the package name Pluginimpl.groovy, note the groovy suffix, then enter it inside, and note that the package name is replaced with your own package name.
package cn.edu.zafu.gradleimport org.gradle.api.Pluginimport org.gradle.api.Projectpublicclass PluginImpl implements Plugin<Project> { void apply(Project project) { project.task(‘testTask‘) << { "Hello gradle plugin" } }}
Then in the Resources/meta-inf/gradle-plugins directory to create a new properties file, note that the name of the file is that you only use the plug-in names, here named plugin.test.properties , enter inside
implementation-class=cn.edu.zafu.gradle.PluginImpl
Note the package name needs to be replaced with your own package name.
This completes the simplest of a gradle plug-in, which has a task called Testtask, executes the task will output a piece of text, just like we output HelloWorld.
Publish to local warehouse
Next, we need to publish the plugin to the MAVEN central repository, and we'll post the plugin to the local repository and add the published code to the Buidl.gradle file under the module project.
repositories { mavenCentral()}group=‘cn.edu.zafu.gradle.plugin‘version=‘1.0.0‘uploadArchives { repositories { mavenDeployer { repository(url: uri(‘../repo‘)) } }}
The definition of the above group and version will be used, as part of the coordinates of the MAVEN library, the group will be used as the coordinates of version groupid,version, and the coordinates of the Artifactid composition is the module name, We let it take an alias modulename. The directory of the MAVEN local repository is then the repo directory under the current project directory.
At this point, the Gradle toolbar on the right will have one more task in the module
Click Uploadarchives This task, you will be under the project a repo directory, which contains the Gradle plugin.
Directory is like this, the specific directory structure and your package name, such as a series of related, Time is my module name.
After posting to the local Maven repository, we use it to add the Gradle.build file to the Android project called the app
{ repositories { maven { url uri(‘../repo‘) } } { classpath ‘cn.edu.zafu.gradle.plugin:time:1.0.0‘ }‘plugin.test‘
The name in the quotation mark behind the Apply plugin is the file name of the previous plugin.test.properties file. The contents of the quotation marks behind class path are the same as MAVEN, as defined in the above grade group,version and modulename.
Sync Gradle, the right app under the other category will be more than a testtask, double-click to execute this task, the console will output just the string we entered
Publish to Jcenter Warehouse
Next we publish it to the Jcenter central warehouse. Refer to an article previously written using Android studio to publish an open source library to the Jcenter Central Library
Add the Build.gradle file in the project root directory.
{ classpath ‘com.android.tools.build:gradle:2.0.0-beta6‘ classpath ‘com.jfrog.bintray.gradle:gradle-bintray-plugin:1.0‘ classpath ‘com.github.dcendents:android-maven-plugin:1.2‘ }
Create a new Bintray.gradle file under the project root path and enter
Apply plugin:' Com.jfrog.bintray 'Apply plugin:' Maven-publish 'defProjectName ="Timeplugin"defMavendesc =' Your desc 'defBASEURL =' Https://github.com/yourBaseUrl 'defSiteURL = BaseUrldefGiturl ="${baseurl}/yourgiturl"defIssueurl ="${baseurl}/yourgitissueurl"defLicenseids = [' Apache-2.0 ']defLicensenames = [' The Apache software License, Version 2.0 ']defLicenseurls = [' Http://www.apache.org/licenses/LICENSE-2.0.txt ']definception =' "defUsername =' Lizhangqu 'Install {repositories {maveninstaller {pom.project {//DescriptionName projectName description Mavendesc URL SiteURL//ArchiveGroupId project.group artifactid archivesbasename version project.version//LicenseInceptionyear Inception licenses {licensenames.eachwithindex {ln, Li- License {Name ln URL Licenseurls[li] }}} developers {developer { Name Username}} SCM {connection Giturl Developerconnection giturl URL SiteURL}}}}}task sou Rcesjar (type: Jar) {from SourceSets.main.allGroovy classifier =' Sources '}task Javadocjar (type: Jar, Dependson:groovydoc) {from groovydoc.destinationdir classifier =' Javadoc '}artifacts {Archives Javadocjar archives sourcesjar}bintray {user = Bintray_user key = Bintray_key Config Urations = [' Archives '] pkg {repo =' maven 'name = ProjectName desc = Mavendesc Websiteurl = SiteURL Issuetrackerurl = Issueurl Vcsurl = g Iturl labels = [' Gradle ',' plugin ',' Time '] Licenses = Licenseids publish =truePublicdownloadnumbers =true}}
Modify the corresponding descriptive text to your own information, especially the first series of DEF definitions, and then add Bintray_user and Bintray_key to the Gradle.properties file.
Apply the grade file in your module
from‘../bintray.gradle‘
The Gradle toolbar on the right will have a few more tasks.
Then we first run the other under the install this task, and then execute bintrayupload this task, if not unexpectedly, upload, and then do not forget to the background add to Jcenter. The word "link to jcenter" will be available after the successful add to Jcenter
Wait patiently for the Add to center success message, and then you can refer directly to the definition of the MAVEN section of the Gradle file under module
maven { uri(‘../repo‘) }
Join in front
jcenter()
The final content is as follows
{ repositories { jcenter() maven { url uri(‘../repo‘) } } { classpath ‘cn.edu.zafu.gradle.plugin:time:1.0.0‘ }‘plugin.test‘
It's that simple, run again for the test success.
Best practices
The source of best practice is from multidex, why, because recently when the number of methods is super, if you choose Multidex, the process of compiling is much slower, in order to detect exactly which step is time-consuming, you need to write a plug-in to count the times of each task execution, So there's a best practice.
Create a new Timelistener.groovy file under the Pluginimpl sibling directory. Input
Package CN. edu. Zafu. Gradleimport org. Gradle. Buildlistenerimport org. Gradle. Buildresultimport org. Gradle. API. Taskimport org. Gradle. API. Execution. Taskexecutionlistenerimport org. Gradle. API. Initialization. Settingsimport org. Gradle. API. Invocation. Gradleimport org. Gradle. API. Tasks. Taskstateimport org. Gradle. Util. ClockClass TimeListener implements Taskexecutionlistener, Buildlistener {private clock clock private times = [] @Over Ride void BeforeExecute (Task task) {clock = new org. Gradle. Util. Clock()} @Override void AfterExecute (Task task, Taskstate taskstate) {def ms = Clock. TimeinmsTimes. Add([MS, task. Path]) Task. Project. Logger. Warn "${task.path} spend ${ms}ms"} @Override void buildfinished (buildresult result) {println"Task spend time:"For (timeinchTimes) {if (time[0] >= -) {printf"%7sms%s\n", Time}}} @Override void buildstarted (Gradle Gradle) {} @Override void Projectsevaluat Ed (Gradle Gradle) {} @Override void projectsloaded (Gradle Gradle) {} @Override void settingsevaluated (Settings Settings) {}}
The Apply method in the Pluginimpl file is then modified to
void apply(Projectproject) { project.gradle.addListener(new TimeListener()) }
Package is released to Jcenter () after completion. Once you reference the plugin, you'll count the time each task executes, such as running the app, and outputting the information like the following.
At the end of best practices, promote this plugin, which I have posted to the Jcenter repository, and add the following code if you want to use it
{ repositories { jcenter() } { classpath ‘cn.edu.zafu.gradle.plugin:time:1.0.0‘ }‘plugin.time‘
Passing parameters
The above is a small test sledgehammer, next we need to get the custom parameters.
Start by following the steps above to create a new module. New Pluginextension.groovy, enter
publicclass PluginExtension { "param1 defaut" "param2 defaut" "param3 defaut"}
Then we want to be able to pass in the nested parameters, create a new Pluginnestextension.groovy, enter
publicclass PluginNestExtension { "nestParam1 defaut" "nestParam2 defaut" "nestParam3 defaut"}
Then create a new Customtask.groovy, inherit the Defaulttask class, and use the @TaskAction annotation notation to implement the method
public class customtask extends defaulttask { @TaskAction void output () {p Rintln "param1 is ${project.pluginext.param1}" println " Param2 is ${project.pluginext.param2} " println " Param3 are ${project.pluginext.para M3} " println " nestparam1 is ${project.pluginext.nestext.nestparam1} " println "NESTPARAM2 is ${project.pluginext.nestext.nestparam2}" println "NESTPARAM3 is ${PROJECT.PLUGINEXT.NESTEXT.NESTPARAM3}" }}
Just do get the parameters and then do the simplest output operation, using ${project.pluginExt.param1} and ${ PROJECT.PLUGINEXT.NESTEXT.NESTPARAM1} to get external parameters.
Don't forget to create a new properties file in the Meta-inf/gradle-plugins directory to specify the plug-in's interface implementation class.
Copy the new Pluginimpl.groovy to the package, modify the Apply method
publicclass PluginImpl implements Plugin<Project> { void apply(Project project) { project.extensions.create(‘pluginExt‘, PluginExtension) project.pluginExt.extensions.create(‘nestExt‘, PluginNestExtension) project.task(‘customTask‘, type: CustomTask) }}
After the plugin is published to local maven, it is referenced.
{ repositories { maven { url uri(‘../repo‘) } } { classpath ‘cn.edu.zafu.gradle.plugin:test:1.0.0‘ }‘plugin.test‘
Define the external parameters, here we define the PARAM1,PARAM2,NESTPARAM1,NESTPARAM2, in addition Param3 and NESTPARAM3 remain the default.
{ param1 = ‘app param1‘ param2 = ‘app param2‘ nestExt{ nestParam1=‘app nestParam1‘ nestParam2=‘app nestParam2‘ }}
Synchronize Gradle, perform customtask.
The code above is very simple and can be seen without explanation, so it is no longer explained.
Reference articles
- Build Artifact Gradle
- Custom Gradle Plugin (i)
- Custom Gradle Plugin (ii)
Source
Finally, the source code of this article
http://download.csdn.net/detail/sbsujjbcy/9451566
How to develop Gradle plugins using Android Studio