1. 程式人生 > >Gradle問題: Android Studio 如何生成jar,生成jar出錯如何處理

Gradle問題: Android Studio 如何生成jar,生成jar出錯如何處理

在升級Android Studio到3.2 Canary 11之後, 專案中無法正常打jar包,報錯如下

Execution failed for task ':migutvbox:lint'.
> Could not resolve all files for configuration ':xxxx:lintClassPath'.
   > Could not resolve com.android.tools.lint:lint-gradle:26.1.2.
     Required by:
         project :xxxx
      > Could not resolve com.android.tools.lint:lint-gradle:26.1.2.
         > Could not get resource 'https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.2/lint-gradle-26.1.2.pom'.
            > Could not HEAD 'https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.2/lint-gradle-26.1.2.pom'.
               > Read timed out
 1:先來看下  如何使用task來打jar包
  1. 新建一個任務,即在module的build.gradle檔案新增task
  2. 指定需要打包的類
  3. 去除不需要打包的類

詳細程式碼如下

   //makeRealeaseJar為task的名稱
    task makeRealeaseJar(type: Jar) {
        //從class檔案生成jar包
        from file('build/intermediates/classes/release')
        //對jar包命名
        archiveName = '50008.jar'
        //生成jar的位置
        destinationDir = file('build/libs')
        //過濾不需要的class
        exclude "**/**/BuildConfig.class"
        exclude "**/**/BuildConfig\$*.class"
        exclude "**/R.class"
        exclude "**/R\$*.class"

        //指定打包的class
        include "com/migu/tv/**/*.class"
    }
    makeRealeaseJar.dependsOn(build)

最後你會在Gradle project中發現這個task的存在
這裡寫圖片描述

雙擊這個紅色方框,即可完成對指定檔案打成jar

 2:再來看下  Could not resolve all files for configuration ':xxxx:lintClassPath如何處理

解決方案

在module的build.gradle檔案中的repositories中新增google(),程式碼如下

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

allprojects {
    repositories {
        jcenter()
        google()
    }
}

你還有可能遇到其他問題,保險起見新增上lintOptions

android {

    lintOptions {
        abortOnError false
        //tasks.lint.enabled = false

        lintConfig file("${project.rootDir}/config/quality/lint/lint.xml")
        // if true, generate an HTML report (with issue explanations, sourcecode, etc)

        //htmlReport true
        // optional path to report (default will be lint-results.html in the builddir)
        //htmlOutput file("$project.buildDir/reports/lint/lint.html")

        xmlReport true
        xmlOutput file("$project.buildDir/reports/lint/lint-results.xml")
    }
 }

1:為什麼添加了google()選項之後,就能正確編譯?

其根本原因還是Gradle外掛不匹配導致的

2:jcenter()含義

他指明瞭gradle從哪裡獲取jar包,如

dependencies {
    compile fileTree(include: '*.jar', dir: 'libs')
    compile files('libs/AuthClient_v1.0.3.jar')
    compile 'com.android.support:support-v4:23.1.1'
//    compile 'com.android.support:appcompat-v7:23.1.1'
//    compile 'com.android.support:support-v13:23.0.1'
//    compile 'com.android.support:design:23.0.1'
}

就指明瞭com.android.support:support-v4:23.1.1這個jar是從jcenter
中獲取的