app 模塊下創建 libs 目錄 (若無):右鍵 app → New → Directory → 命名 libs。.jar 文件複製到 app/libs/ 下。build.gradle 添加依賴。app/build.gradle:dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar']) // 自動包含 libs 下所有 jar
// 或顯式指定
implementation files('libs/your-library.jar')
}
若庫發布到 Maven Central / JitPack / JCenter:
// Project/build.gradle
allprojects {
repositories {
google()
mavenCentral()
maven { url 'https://jitpack.io' } // JitPack 常用於 GitHub 庫
}
}
// app/build.gradle
dependencies {
// 格式: 'groupId:artifactId:version'
implementation 'com.github.User:Repo:Tag' // JitPack 格式
implementation 'com.squareup.okhttp3:okhttp:4.11.0' // Maven Central 示例
}
優點: 版本管理、傳遞依賴自動解析、一鍵升級、無需手動複製文件。
mvn install:install-file -Dfile=your.jar -DgroupId=com.local -DartifactId=yourlib -Dversion=1.0 -Dpackaging=jarmavenLocal() 加入 repositories。implementation 'com.local:yourlib:1.0'。| 現象 | 原因 | 解決 |
|---|---|---|
| 右鍵 JAR 無 "Add As Library" | 視圖非 Project 模式 / 文件不在模塊目錄下 | 切換 Project 視圖,確保 JAR 在 app/libs/ |
| 導入後找不到類/方法 | JAR 版本錯誤 / 未同步 Gradle / 依賴衝突 | Sync Project with Gradle Files;檢查 External Libraries 列表 |
| Duplicate class 錯誤 | 同一類存在於多個 JAR / 依賴傳遞衝突 | 用 exclude group: 'xxx' 排除傳遞依賴;或升級統一版本 |
| Could not find ... | 倉庫地址缺失 / 坐標錯誤 / 網絡不通 | 添加 jitpack.io/mavenCentral();核對 groupId/artifactId/version |
gradle.properties 統一管理版本號:okhttpVersion=4.11.0,依賴中用 implementation "com.squareup.okhttp3:okhttp:$okhttpVersion"。./gradlew dependencyUpdates (需插件) 檢查可升級依賴。**Android Studio 導入 JAR 兩大主流路徑:**
1. **手動複製到 app/libs/ → 右鍵 Add As Library** (適用離線/私有 JAR)。
2. **在 build.gradle 添加 implementation 'group:artifact:version'** (適用 Maven/JitPack 庫,**強烈推薦**)。
GitHub 庫通常提供 JitPack 坐標,直接複製到 dependencies 即可,無需手動下載 JAR。