Detailed Use of Gradle in Android Studio

Keywords: Android Gradle Java Junit

1) Basic configuration

  1. build configuration

    buildscript {
     repositories {
         jcenter() 
     }
     dependencies {
         classpath 'com.android.tools.build:gradle:1.2.3'
     } 
    }

    Android script

    apply plugin: 'com.android.application'

    Android configuration

    android {
     compileSdkVersion 22
     buildToolsVersion "22.0.1"
    }

    Project structure

    MyApp
    ├── build.gradle
    ├── settings.gradle
    └── app
        ├── build.gradle
        ├── build
        ├── libs
        └── src
            └── main
                ├── java
                │   └── com.package.myapp
                └── res
                    ├── drawable
                    ├── layout
                    └── etc.
  2. Gradle Wrapper structure (these new projects were added to the user without re-adding)

    myapp/
     ├── gradlew 
     ├── gradlew.bat
     └── gradle/wrapper/
         ├── gradle-wrapper.jar
         └── gradle-wrapper.properties

    Run build tasks - List all available tasks

    $ ./gradlew tasks

    Generating App-debug.apk tasks

    $ ./gradlew assembleDebug
    
    # Apk path: MyApp/app/build/outputs/apk
  3. Manual import of Eclipse-Android project (auto-import please click Next)
    Create the build.gradle file under the project path:

    buildscript {
      repositories {
          jcenter() 
      }
      dependencies {
          classpath 'com.android.tools.build:gradle:1.2.3'
      }
    }
    apply plugin: 'com.android.application'
    android {
      compileSdkVersion 22
      buildToolsVersion "22.0.1"
      sourceSets {
          main {
              manifest.srcFile 'AndroidManifest.xml'
              java.srcDirs = ['src']
              resources.srcDirs = ['src']
              aidl.srcDirs = ['src']
              renderscript.srcDirs = ['src']
              res.srcDirs = ['res']
              assets.srcDirs = ['assets']
          }
          androidTest.setRoot('tests')
      } 
    }
    dependencies {
      compile fileTree(dir: 'libs', include: ['*.jar'])
    }

    PS can also copy and paste the source code of the Eclipse-Android project into the Android Studio project

2) Custom Configuration

  1. Gradle All File Structures

    MyApp
    ├── build.gradle
    ├── settings.gradle
    └── app
        └── build.gradle

    settings.gradle

    include ':app'

    MyApp/build.gradle

    buildscript {
     repositories {
         jcenter()
     }
     dependencies {
         classpath 'com.android.tools.build:gradle:1.2.3'
     } 
    }
    allprojects {
     repositories {
         jcenter() 
     }
    }

    MyApp/app/build.gradle

    apply plugin: 'com.android.application'
    android {
     compileSdkVersion 22
     buildToolsVersion "22.0.1"
     defaultConfig {
         applicationId "com.gradleforandroid.gettingstarted"
         minSdkVersion 14
         targetSdkVersion 22
         versionCode 1
         versionName "1.0"
     }
     buildTypes {
         release {
             minifyEnabled false
             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
         }
     } 
    }
    dependencies {
     compile fileTree(dir: 'libs', include: ['*.jar'])
     compile 'com.android.support:appcompat-v7:22.2.0'
    }
  2. Basic task

    $. / gradlew assemble - Create apk s for all build types
     $. / gradlew check runs all checks, such as Android Lint, and terminates tasks if problems are found
     $. / gradlew build runs the above two tasks
     $. / gradlew clean - Clear the generated apk
    ++++
    $. / gradlew connected Check - Running tests on devices
     $. / gradlew device Check - remote device run test
     $. / gradlew installDebug/installRelease - Install the specified version at the device vendor
     $. / gradlew uninstall - uninstall

  3. Parameter settings for different versions of Build Types - Build Config/Resource Value

    android {
      buildTypes {
          debug {
              applicationIdSuffix ".debug"
              buildConfigField "String", "API_URL","\"http://test.example.com/api\""
              buildConfigField "boolean", "LOG_HTTP_CALLS", "true"
              resValue "string", "app_name", "Example DEBUG"
          }
          release {
              buildConfigField "String", "API_URL", "\"http://example.com/api\""
              buildConfigField "boolean", "LOG_HTTP_CALLS", "false"
              resValue "string", "app_name", "Example"
          }
      }
    }
  4. Global settings (build.gradle in the project root directory)

    allprojects {
      apply plugin: 'com.android.application'
      android {
          compileSdkVersion 22
          buildToolsVersion "22.0.1"
      } 
    }

    Setting global parameters

    ext {
      compileSdkVersion = 22
      buildToolsVersion = "22.0.1"
    }

    Use parameters in MyApp/app/build.gradle

    android {
      compileSdkVersion rootProject.ext.compileSdkVersion
      buildToolsVersion rootProject.ext.buildToolsVersion
    }
  5. Default Tasks (MyApp/build.gradle)

    defaultTasks 'clean', 'assembleDebug'

3) Dependence Management

  1. Warehouse
    Preset Configuration Warehouse

    repositories {
     mavenCentral()
     jcenter()
     mavenLocal()
    }

    Remote warehouse

    repositories {
     maven {
         url "http://repo.acmecorp.com/maven2"
         credentials {
             username 'user'
            password 'secretpassword'
         }
     }
     ivy {
         url "http://repo.acmecorp.com/repo"
     }
    }

    Local warehouse

    repositories {
     maven {
         url "../repo"
     }
    }
  2. Local dependence
    Project Document Dependence

    dependencies {
      compile fileTree(dir: 'libs', include: ['*.jar'])
    }

    Primary Library Structure and Configuration

    # Structure:
    app
     ├── AndroidManifest.xml
     └── jniLibs
         ├── armeabi
         │   └── nativelib.so
         ├── armeabi-v7a
         │   └── nativelib.so
         ├── mips
         │   └── nativelib.so
         └── x86
             └── nativelib.so
    # To configure:
    android {
      sourceSets.main {
          jniLibs.srcDir 'src/main/libs'
      }
    }

    Libray project

    # Modify the Android plug-in:
    apply plugin: 'com.android.library'
    # settings.gradle added a new libray project:
    include ':app', ':library'
    # The library project is referenced in app:
    dependencies {
      compile project(':library')
    }

    .aar file

    # Generate arr
    repositories {
      flatDir {
          dirs 'aars' 
      }
    }
    # Using aar
    dependencies {
      compile(name:'libraryname', ext:'aar')
    }
  3. Dependency concept

    # Dynamic version
    dependencies {
      compile 'com.android.support:support-v4:22.2.+'
      compile 'com.android.support:appcompat-v7:22.2+'
      compile 'com.android.support:recyclerview-v7:+'
    }
  4. Adding dependencies in Android Studio


IV) Constructing Variants

  • Construction type
    android {
     buildTypes {
         # release type
         release {
             minifyEnabled false
             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
         }
         # The staging type replicates the debug type
         staging.initWith(buildTypes.debug)
         staging {
             applicationIdSuffix ".staging"
             versionNameSuffix "-staging"
             buildConfigField "String", "API_URL", "\"http://staging.example.com/api\""
         }
     } 
    }
  • Product pattern
    android {
     productFlavors {
         red {
             applicationId 'com.gradleforandroid.red'
             versionCode 3
         }
         blue {
             applicationId 'com.gradleforandroid.blue'
             minSdkVersion 14
             versionCode 4
         } 
     }
    }
  • Build Variants
    < to be continued >
  • Signature configuration
    android {
     signingConfigs {
         staging.initWith(signingConfigs.debug)
         release {
             storeFile file("release.keystore")
             storePassword"secretpassword"
             keyAlias "gradleforandroid"
             keyPassword "secretpassword"
         } 
     }
    }

5) Multi-module Construction Management

  1. Accelerate construction
    Add in gradle.properties:
    org.gradle.parallel=true

VI) Testing

  1. unit testing
    Using JUnit

    # Structure:
    app
    └─── src
    ├─── main
    │ ├─── java
         │    │    └─── com.example.app
         │    └───res
         └─── test
              └─── java
                   └─── com.example.app
    # Dependence:
    dependencies {
     testCompile 'junit:junit:4.12'
    }

    Using Robolectric

    # Dependence:
    apply plugin: 'org.robolectric'
     dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:22.2.0'
        testCompile 'junit:junit:4.12'
        testCompile'org.robolectric:robolectric:3.0'
        testCompile'org.robolectric:shadows-support:3.0'
    }
    # Demo: 
    @RunWith(RobolectricTestRunner.class)
    @Config(manifest = "app/src/main/AndroidManifest.xml", sdk = 18)
    public class MainActivityTest {
     @Test
     public void clickingButtonShouldChangeText() {
         AppCompatActivity activity = Robolectric.buildActivity(MainActivity.class).create().get();
         Button button = (Button) activity.findViewById(R.id.button);
         TextView textView = (TextView) activity.findViewById(R.id.label);
         button.performClick();
         assertThat(textView.getText().toString(), equalTo(activity.getString(R.string.hello_robolectric)));
     } 
    }
  2. functional testing
    Use Espresso

    < to be continued >
  3. Test coverage
    Using Jacoco

    < to be continued >

7) Creating Tasks and Plug-ins

  1. < to be continued >

Configuration CI

  1. < to be continued >

9) Custom Configuration - Advancement

  1. Reduce apk file size
    Use ProGuard
    android {
     buildTypes {
         release {
             minifyEnabled true
             shrinkResources true
             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
         }
     } 
    }
    Shrinking Resource Files - Automation (<Manual to Continue>)
    android {
     buildTypes {
         release {
             minifyEnabled true
             shrinkResources true
         }
     } 
    }
  2. Accelerate construction

    org.gradle.parallel=true # Parallel construction
    org.gradle.daemon=true # Open the Gradle daemon
    org.gradle.jvmargs=-Xms256m -Xmx1024m # Configure JVM < Refer to Figure below >


    Using Profiling

    < to be continued >

    Use Jack(Java Android Compiler Kit) and Jill(Jack Intermediate Library Linker)

    < to be continued >
  3. Ignore Lint

    android {
      lintOptions {
          abortOnError false
      }
    }
  4. Using Ant

    < to be continued >
  5. app Packaging - Advancement
    Split apk

    android {
      splits {
          density {
              enable true
              exclude 'ldpi', 'mdpi'
              compatibleScreens 'normal', 'large', 'xlarge'
          }
      } 
    }
    //Generate results:
    app-hdpi-release.apk
    app-universal-release.apk
    app-xhdpi-release.apk
    app-xxhdpi-release.apk
    app-xxxhdpi-release.apk

Quote:

  • <Gradle for Android>

Posted by RockRunner on Wed, 27 Mar 2019 11:39:28 -0700