Android uses Gradle dependency to configure compile implementation and api

  • 2021-10-15 11:24:00
  • OfStack

Preface

After AndroidStudio was upgraded to 3.0, gradle was upgraded to 3.0. 0.

When the gradle plug-in is upgraded to 3.0. 0 and above, we will find that when adding dependencies to gradle, you will be recommended to use implementation or api instead of compile. Today, we will briefly introduce the use and difference between the two!


classpath 'com.android.tools.build:gradle:3.0.0'

When creating a new Android project, the dependency in build. gradle defaults to implementation instead of the previous compile. In addition, gradle version 3.0. 0 and above, there is also a dependent instruction api. This paper mainly introduces the difference between implementation and api.

Dependencies in the build. gradle file of the default generated app for the new project:


dependencies { 
 implementation fileTree(include: ['*.jar'], dir: 'libs') 
 implementation 'com.android.support:appcompat-v7:26.1.0' 
 implementation 'com.android.support.constraint:constraint-layout:1.0.2'  
 testImplementation 'junit:junit:4.12' 
 androidTestImplementation 'com.android.support.test:runner:1.0.1' 
 androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

api instruction

It's exactly the same as the compile command. It doesn't make any difference. You change all compile to api, and there is nothing wrong with it.

implementation instruction

The characteristic of this directive is that for dependencies compiled with this command, projects that have dependencies on this project will not be able to access any programs in the dependencies compiled with this command, that is, the dependencies will be hidden internally and not exposed externally.

Simply put, dependencies using implementation instructions will not be passed. For example, one module is testLib, and testLib depends on Glide:


implementation 'com.github.bumptech.glide:glide:3.8.0'

At this time, the java code in testsdk can access Glide.

The other module is app, and app depends on testLib:


implementation project(':testLib')

At this time, because testsdk uses implementation instruction to rely on Glide, Glide cannot be referenced in app.

However, if testLib uses api to reference Glide:


api 'com.github.bumptech.glide:glide:3.8.0'

Then the effect of compile instruction before gradle3.0. 0 is exactly the same, and module of app can also refer to Glide, which is the difference between api and implementation.

Recommendations

compile has been discarded in the 3. x version of gradle and will be removed by google at the end of 2018, so don't use compile The dependency should first be set to implementation, implementation if there is no error, and api instruction if there is error

Summary:


Related articles: