紀錄一下如何純粹使用終端機指令,編譯 android APK
事前準備
- Java,儘量使用最新版的 Java
- Android SDK
- 如果已經安裝 Android Studio,那就不用另外安裝
- 如果不想安裝 Android Studio,那可以到Android Studio 下載頁下方的《僅限指令列工具》那可以下載。但使用這方法,要另行設
ANDROID_HOME
的環境變數 - 如果是用 CI/CD, Github Action 已經有人寫好了:android-actions/setup-android
- 使用 Docker ,可以使用thyrlian/android-sdk
編譯開發用 APK
在 Android 專案,執行以下指令
$ ./gradlew assembleDebug --warning-mode all
如果是 windows 使用者,改成
> gradlew.bat assembleDebug --warning-mode all
編譯好的 apk 檔會放在 {專案資料夾}/app/build/outputs/apk/debug
編譯發布用的正式 APK
簽章
首先先建立簽章
keytool -genkey -v \
-keystore my-keystore.keystore \
-alias my-project
-keyalg RSA
-keysize 2048
-validity 10000
-dname "CN=JohnSmith, OU=IT, O=MyOrganization, L=North Dist, S=Taipei City, C=Taiwan"
-storepass 1qaz2wsx
-keypass 1qaz2wsx
- keytool 是 JDK 內包含的軟體。
- 上述有特別標記的請依自己需求作修改
- 上述雖然有分 storepass 和 keypass 兩個參數,但如果兩個參數不同會跳出警告,所以這邊保持相同
這邊建立的 keystore 檔放在專案資料夾即可
.properties
再來在專案資料夾建立 .properties 檔案(例如{專案資料夾}/keystore.properties
),檔案內容如下
MYAPP_RELEASE_STORE_FILE=my-keystore.keystore
MYAPP_RELEASE_KEY_ALIAS=my-project
MYAPP_RELEASE_STORE_PASSWORD=1qaz2wsx
MYAPP_RELEASE_KEY_PASSWORD=1qaz2wsx
這邊的參數值依照先前建立的 keystore 自行修改
修改 {專案資料夾}/app/build.gradle
{專案資料夾}/app/build.gradle
進行以下修改
最上方加上
def keystorePropertiesFile = rootProject.file("keystore.properties") def keystoreProperties = new Properties() keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
其中,第一行是告知你的 .properties 檔的位置,默認路徑是
{專案資料夾}
如果你放在其他資料夾,例如{專案資料夾}/keystore
,那就要改成rootProject.file("keystore/keystore.properties")
android{} 區塊內加上
signingConfigs { release { keyAlias keystoreProperties['MYAPP_RELEASE_KEY_ALIAS'] keyPassword keystoreProperties['MYAPP_RELEASE_KEY_PASSWORD'] storeFile file(keystoreProperties['MYAPP_RELEASE_STORE_FILE']) storePassword keystoreProperties['MYAPP_RELEASE_STORE_PASSWORD'] } }
這邊根據 keystore.properties 內的 property name 自行更動
在
android{ buildTypes{ release{} } }
內加上signingConfig signingConfigs.release
修改好的 build.gradle 大致如下:
def keystorePropertiesFile = rootProject.file("keystore.properties")
def keystoreProperties = new Properties()
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
apply plugin: 'com.android.application'
android {
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
/* 中略*/
}
signingConfigs {
release {
keyAlias keystoreProperties['MYAPP_RELEASE_KEY_ALIAS']
keyPassword keystoreProperties['MYAPP_RELEASE_KEY_PASSWORD']
storeFile file(keystoreProperties['MYAPP_RELEASE_STORE_FILE'])
storePassword keystoreProperties['MYAPP_RELEASE_STORE_PASSWORD']
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
/* 中略*/
}
dependencies {
/* 中略*/
}
/* 下略*/
編譯
完成上述步驟後,執行以下指令即可
$ ./gradlew assembleRelease --warning-mode all
如果是 windows 使用者,改成
> gradlew.bat assembleRelease --warning-mode all
編譯好的 apk 檔會放在 {專案資料夾}/app/build/outputs/apk/release
資料夾中
沒有留言:
張貼留言