一、新建一個Android項目
首先,在Android Studio中創建一個新的Android項目。可以選擇空白活動或默認活動(Blank Activity or Default Activity)。在這裡,我們選擇默認活動。
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.myapplication.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
二、配置Gradle文件
接下來,在app文件夾中找到build.gradle(Module:app)文件,並添加以下幾行代碼以構建APK文件。例如,我們可以在defaultConfig標記中設置應用程序ID和版本代碼。為了使應用程序更易於識別和分發,我們可以設置應用程序版本名稱。
android {
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
三、生成unsigned APK
現在,我們可以生成沒有簽名的APK文件。要生成unsigned APK文件,請按照以下步驟:
- 在Android Studio的「菜單欄」中選擇:Build -> Generate Signed APK…
- 在彈出窗口中選擇「Create new…」
- 在彈出窗口中輸入密鑰的詳細信息(如密鑰文件、密碼、別名和密碼)
- 單擊「Next」按鈕,並選擇「unsigned」選項。
- 繼續單擊「Next」按鈕,並在彈出窗口中選擇一個位置來保存apk文件。單擊「Finish」按鈕並完成生成。
四、生成signed APK
請注意,由於unsigned APK文件不能安裝,必須通過「簽名」應用程序以生成安裝程序。要生成簽名APK文件,請按照以下步驟:
- 在Android Studio的「菜單欄」中選擇:Build -> Generate Signed APK…
- 選擇此前創建的密鑰文件並輸入密碼和別名等信息。
- 單擊「Next」按鈕,並驗證APK文件的信息。
- 繼續單擊「Next」按鈕,並在彈出窗口中選擇一個位置來保存apk文件。單擊「Finish」按鈕並完成生成。
五、安裝APK文件
生成signed APK後,可以通過以下兩種方式將其安裝到設備上:
- 通過Android Studio安裝:右鍵單擊生成的APK文件,並選擇「Show in Explorer」選項。從文件管理器中打開生成的APK文件,並將其拖放到已連接的設備的內部存儲中。單擊文件以在設備上打開安裝程序。
- 通過命令行安裝:在Android SDK的platform-tools目錄中打開命令行,並輸入以下命令:
adb install [-r] [-s] path_to_apk_file
其中,-r選項用於重新安裝,-s選項用於將應用程序安裝在SD卡上(而不是內部存儲器中)。
至此,已成功使用Android Studio生成APK文件。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/200554.html