2016年7月6日 星期三

Android 用 WebView 建立 app

參考文章:  https://developer.android.com/guide/webapps/webview.html
1. 用 Android studio 開啟新的空白專案,
2. 在檔案 activity_main.xml 加入 WebView 標籤讓 WebView 做顯示:

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

3. 在檔案 AndroidManifest.xml 加入開啟網路權限, 務必將該權限放置在 manifest 標籤後面applicaton 標籤前面.
<manifest
...
<uses-permission android:name="android.permission.INTERNET" />
...
<application

4. 使用滑鼠右鍵在 Android Studio 的 app 點一下叫出選單, 使用預設的名字後按 Finish. 預設會將 file:///android_asset/ 指向 main/assets該目錄:

        app -> New -> Folder -> Assets Folder

5. 在主程式 MainActivity.java 呼叫 WebView 的程式碼, 並開放使用 Javascript:

        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebChromeClient(new WebChromeClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("file:///android_asset/index.html");

6. 將所有要瀏覽的檔案(包含 index.html)放進 assets 目錄下,完成後在 Android Studio 檔 menu 上 Build -> Build APK 產生 Android apk 檔

7. 如果要在 WebView 播放聲音檔, 參考文章用 Java 寫一個原生的類別:

http://www.codeproject.com/Tips/677841/Playing-Audio-on-Android-from-an-HTML-File

沒有留言: