【實作紀錄】Android Studio 打包Webview APK

Ray
Oct 30, 2021

透過Native App(這邊使用Android studio的kotlin)上的Webview,來顯示JavaScript的畫面的程式稱為Hybrid App。

Hybrid App的好處是,假設我下載了一個連到A網站的Hybrid App,這樣我只要更新A網站的內容,這個App就會跟著更新,不需要再自己下載更新。另一個好處是,只要會本文的內容(輸出Webview APK),這樣就算只會JavaScript,也能做出App。

壞處就是,效能層面會比純Native較差,畢竟Hybrid App是透過瀏覽器開啟,不過這個部分也隨著時間在優化。還有一個問題是瀏覽器無法直接存取Native的裝置資訊(ex.藍芽)。

主要流程

  • 建立Webview App
  • 打包Apk

建立Webview App

1.新建專案

語言選Kotlin(Java跟Kotlin語法會有些不一樣)

2.增加網路許可權

AndroidManifest.xml

因為我們要建立有Webview的App,因此需要開啟網路許可,如果你的其他App不需要網路的話則這行就不是必須的。

其他許可權的還有像是:允許使用相機、藍芽操作..等等(參考)

3.清除Layout

將上面的Layout刪除,更改為Webview
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
點選後案刪除,把Hello World拿掉

4.加入Webview程式碼

import android.webkit.WebView
import android.webkit.WebViewClient

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val webview = findViewById(R.id.webview) as WebView
val webSettings = webview.settings
webSettings.javaScriptEnabled = true
setContentView(webview)
webview.webViewClient = WebViewClient()
webview.loadUrl("https://forum.gamer.com.tw/B.php?bsn=60076")
}
}

這時候打開看,會發現App上面的Title有專案名稱

5.移除標題列

找到themes.xml並修改<style>的parent屬性

<style name="<專案名稱>" parent="Theme.AppCompat.NoActionBar">

備註

  1. 新版Android Studio已經使用themes.xml替代掉原本的styles.xml
  2. 會根據用戶是否使用深色模式決定套用的樣式,themes.xml或是themes.xml(night)
已移除標題列

打包APK

1.選擇

2.建立Key Store資訊

Key store path:金鑰要儲存在哪
Key store path password:存取這個檔案的密碼
Key Alias: 金鑰的名字
Password: Confirm: 金鑰的密碼
Validity years: 金鑰有效時間

Certificate(可以理解成建立這個App的單位或人的相關資訊)
First and LastName :建立人
Organizational Unit: 公司單位(ex:工程部 之類的)
Organization:公司名稱
City or Locality:城市或國家
State or Province:國或省
CountryCode(XX):國家代碼(TW)

3.Build

Release為正式版,Debug為測試版(一般Debug版本無法上架如play商店等)

Debug APK輸出預設路徑

C:\Users\使用者\AndroidStudioProjects\專案名稱\app\debug

Release APK輸出預設路徑

C:\Users\使用者\AndroidStudioProjects\專案名稱\app\release

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response