Android Studio中Gradle使用詳解

來源:互聯網
上載者:User

標籤:

一)基本配置
  1. build配置

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

    Android指令碼

    apply plugin: ‘com.android.application‘

    Android配置

    android { compileSdkVersion 22 buildToolsVersion "22.0.1"}

    項目結構

    MyApp├── build.gradle├── settings.gradle└── app    ├── build.gradle    ├── build    ├── libs    └── src        └── main            ├── java            │   └── com.package.myapp            └── res                ├── drawable                ├── layout                └── etc.
  2. Gradle Wrapper結構(這些建立項目時都添加給了使用者,不需要重新添加)

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

    運行build任務 - 列出所有可用任務

    $ ./gradlew tasks

    產生App-debug.apk任務

    $ ./gradlew assembleDebug# Apk路徑: MyApp/app/build/ outputs/apk
  3. 手動匯入Eclipse-Android項目(自動匯入請連續點“下一步”)
    在項目路徑下建立build.gradle檔案:

    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 也可以複製粘貼Eclipse-Android項目的原始碼到Android Studio的項目裡

二)自訂配置
  1. Gradle所有檔案結構

    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. 基礎任務

    $ ./gradlew assemble -為所有構建類型建立apk$ ./gradlew check 運行所有的檢查,比如說Android Lint,如果發現問題可終止任務$ ./gradlew build 運行以上兩個任務$ ./gradlew clean -清除產生的apk++++$ ./gradlew connectedCheck - 在裝置上運行測試$ ./gradlew deviceCheck - 遠程裝置運行測試$ ./gradlew installDebug/installRelease - 在裝置商安裝指定版本$ ./gradlew uninstall - 卸載

  3. Build Types不同版本的參數設定 - BuildConfig/Resource Value

    android {  buildTypes {      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. 全域設定(項目根目錄的build.gradle)

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

    設定全域參數

    ext {  compileSdkVersion = 22  buildToolsVersion = "22.0.1"}

    在MyApp/app/build.gradle裡面使用參數

    android {  compileSdkVersion rootProject.ext.compileSdkVersion  buildToolsVersion rootProject.ext.buildToolsVersion}
  5. 預設任務(MyApp/build.gradle)

    defaultTasks ‘clean‘, ‘assembleDebug‘
三) 依賴管理
  1. 倉庫
    預設配置倉庫

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

    遠程倉庫

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

    本地倉庫

    repositories { maven {     url "../repo" }}
  2. 本地依賴
    專案檔依賴

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

    原生庫結構與配置

    # 結構:app ├── AndroidManifest.xml └── jniLibs     ├── armeabi     │   └── nativelib.so     ├── armeabi-v7a     │   └── nativelib.so     ├── mips     │   └── nativelib.so     └── x86         └── nativelib.so# 配置:android {  sourceSets.main {      jniLibs.srcDir ‘src/main/libs‘  }}

    Libray項目

    # 修改Android外掛程式:apply plugin: ‘com.android.library‘# settings.gradle新增libray項目:include ‘:app‘, ‘:library‘# app內引用library項目:dependencies {  compile project(‘:library‘)}
  3. 依賴概念

    <待續>
  4. Android Studio內添加依賴


四)構建變體
  • <待續>
五)多模組構建管理
  1. 加速構建
    在gradle.properties裡面添加:org.gradle.parallel=true
六) 測試
  1. 單元測試
    使用JUnit

    # 結構:app└─── src├─── main│ ├─── java     │    │    └─── com.example.app     │    └───res     └─── test          └─── java               └─── com.example.app# 依賴:dependencies { testCompile ‘junit:junit:4.12‘}

    使用Robolectric

    # 依賴: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. 功能測試
    使用Espresso

    <待續>
  3. 測試覆蓋度
    使用Jacoco

    <待續>
七)建立任務與外掛程式
  1. <待續>
八)配置CI
  1. <待續>
九)自訂配置 - 進階
  1. 縮減apk檔案大小
    使用ProGuard
    android { buildTypes {     release {         minifyEnabled true         proguardFiles getDefaultProguardFile(‘proguard-android.txt‘), ‘proguard-rules.pro‘     } } }
    收縮資源檔 - 自動 (<手動待續>)
    android { buildTypes {     release {         minifyEnabled true         shrinkResources true     } } }
  2. 加速構建

    org.gradle.parallel=true # 並行構建org.gradle.daemon=true # 開啟Gradle守護進程org.gradle.jvmargs=-Xms256m -Xmx1024m # 配置JVM<參照>


    使用Profiling

    <待續>

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

    <待續>
  3. 忽略Lint

    android {  lintOptions {      abortOnError false  }}
  4. 使用Ant

    <待續>
  5. app打包 - 進階
    分割apk

    android {  splits {      density {          enable true          exclude ‘ldpi‘, ‘mdpi‘          compatibleScreens ‘normal‘, ‘large‘, ‘xlarge‘      }  } }產生結果:app-hdpi-release.apkapp-universal-release.apkapp-xhdpi-release.apkapp-xxhdpi-release.apkapp-xxxhdpi-release.apk



文/田浩浩_DockOne(簡書作者)
原文連結:http://www.jianshu.com/p/02cb9a0eb2a0
著作權歸作者所有,轉載請聯絡作者獲得授權,並標註“簡書作者”。

Android Studio中Gradle使用詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.