Home > Software design >  Android gradle custom Plugin error after updating android gradle plugin to 7.0
Android gradle custom Plugin error after updating android gradle plugin to 7.0

Time:10-21

Following is my code for custom plugin

import com.android.annotations.NonNull;
import com.android.build.gradle.LibraryExtension;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;


public class CustomPlugin implements Plugin<Project> {

@Override
public void apply(@NonNull Project project) {
    project.getPluginManager().withPlugin("com.android.library", plugin -> {
        //code here
    });
}

}

After upgrading android gradle plugin from 4.2.1 to 7.0 above custom plugin code showing error: package com.android.annotations does not exist

How to fix this error?

CodePudding user response:

As I work in the same project as alphanso and took over the AGP upgrade from him, here is what I finally found out:

The code sits in the .buildSrc directory of our project and is compiled there using the Gradle plugins java-library and java-gradle-plugin.

Therefore android.useAndroidX=true has no effect as this works only if you use the Android plugins, either com.android.library or com.android.application.

The root cause of the suddenly missing classes (we had a few other ones missing from sub packages of com.android.build as well) was somewhere else:

With AGP 7.0 most library dependencies of com.android.tools.build:gradle changed from "compile time" to "run time" as you can see here:

AGP 4.2.2: https://mvnrepository.com/artifact/com.android.tools.build/gradle/4.2.2

AGP 7.0: https://mvnrepository.com/artifact/com.android.tools.build/gradle/7.0.0

This means that when switching to AGP 7.x you must add the missing dependencies manually.

In our case adding

implementation "com.android.tools:common:30.0.3"

solved the problem.

CodePudding user response:

In android gradle plugin 7.0, the use of AndroidX Libraries is recommended. First, in your gradle.properties file, enable AndroidX by adding

android.useAndroidX=true

Add these dependencies also (To set up the other androidx libraries),

implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

Sync your gradle files and then change the import com.android.annotations.NonNull to androidx.annotations.NonNull

  • Related