안드로이드

[Android] Anroid local html 불러오기 (assets/www/MyHome.html 호출) (2/3)

IT꿈나무 2021. 9. 29. 17:39
반응형

목적:

안드로이드 로컬에서 Html의 javascript를 호출 하는 코드 구현.

 

방법:

1) 메니페스트에서는 <uses-permission android:name="android.permission.INTERNET" /> 추가 필요

2) WebView에서는 mWebView.getSettings().setJavaScriptEnabled(true); // 자바스크립트 사용 허용!!

3) assets 폴더 추가.

4)html 코드 assets/www/MyHome.html 복사. (html 내용은 이전(1/3) 참고.

 

3) #특이사항 alert는 아래 상속 코드 구현 필요.

        this.mWebView.setWebChromeClient(new WebChromeClient(){

            @Override   //구현 하지 않으면 alert 반응 안함!! consol.log 생활화!! ^_^
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                Log.i(getClass().getName()+"jky", "onJsAlert() url:"+url+", message:"+message);
                //return super.onJsAlert(view, url, message, result);
                new AlertDialog.Builder(view.getContext())
                        .setTitle("")
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok,
                                new AlertDialog.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        result.confirm();

                                    }
                                })
                        .setCancelable(false)
                        .create()
                        .show();

                return true;
            }

 

구현 내용:

actvity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello My Webview!"
        android:textSize="30dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <!-- android:layout_height="0dp 공간 채우기!! -->
    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.mywebview;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private WebView mWebView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.mWebView = findViewById(R.id.webView);
        mWebView.getSettings().setJavaScriptEnabled(true); // 자바스크립트 사용 허용!!

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

//        this.mWebView.setWebViewClient(new WebViewClient(){ }); // 사용 안하면 URL 스킴이 외부 브라우져 띄우면서 그냥 됨.

//        //sub webView 처리 //WebView 처리 (처리하지 않으면 http 접속시 외부뷰어 실행)
        this.mWebView.setWebChromeClient(new WebChromeClient(){

            @Override   //구현 하지 않으면 alert 반응 안함!! consol.log 생활화!! ^_^
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                Log.i(getClass().getName()+"jky", "onJsAlert() url:"+url+", message:"+message);
                //return super.onJsAlert(view, url, message, result);
                new AlertDialog.Builder(view.getContext())
                        .setTitle("")
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok,
                                new AlertDialog.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        result.confirm();

                                    }
                                })
                        .setCancelable(false)
                        .create()
                        .show();

                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                Log.i(getClass().getName()+"jky", "onJsConfirm() url:"+url+", message"+message);
                //return super.onJsConfirm(view, url, message, result);

                new AlertDialog.Builder(view.getContext())
                        .setTitle("")
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        result.confirm();

                                    }
                                })
                        .setNegativeButton(android.R.string.cancel,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        result.cancel();
                                    }
                                })
                        .create()
                        .show();
                return true;
            }

        });

        this.mWebView.loadUrl("file:///android_asset/www/MyHome.html");

    }
}

 

MyHome.html

<html>
    <head>
 
        <meta charset="utf8">
        <script type="text/javascript">
            
            window.onload = function() {//윈도우가 열리면
                document.getElementById("A").onclick = function() {
                    console.log("A함수호출")
                    alert("A함수호출");
                }
 
                document.getElementById("B").onclick = function() {
                    console.log("B함수호출")
                    alert("B함수호출");
                }
            }
            click_a = function(str){
                if(str){
                    console.log("click_a 함수호출"+str)
                    alert("click_a 함수호출"+str);
                }else{
                    console.log("click_a 함수호출")
                    alert("click_a 함수호출");
                }
            }
            click_b = function(){
                console.log("click_b 함수호출")
                alert("click_b 함수호출");
            }
            
       </script>
 
    </head>
 
    <body>
 
        <input type="button" value="A함수호출" id="A"/>
        <input type="button" value="B함수호출" id="B"/>
        <br>
        <input type="button" value="click_A 함수호출" onclick="click_a()"/>
        <input type="button" value="click_A 함수호출(click했어)" onclick="click_a('click 했어')"/>
        <br>
        <input type="button" value="click_B 함수호출" onclick="click_b()"/>
        <br>
        Android(aos) 호출 관련 (bridge는 aos)
        <br>
        <input type="button" value="aos.click_t 함수호출" onclick="window.aos.click_t()"/> <br>
        <input type="button" value="aos.click_toast 함수호출" onclick="window.aos.click_toast()"/>

    </body>
 
</html>

 

디버깅 및 결과

 

프로젝트 코드:

MyWebView.zip
0.36MB

참고자료:

[1] html javascript 구현,

https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=tkddlf4209&logNo=220512073357 

[2]안드로이드 로컬(assets) html 불러오기, 

https://dev.eyegood.co.kr/entry/Android-Local-Html-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0assets%ED%8F%B4%EB%8D%94%EC%83%9D%EC%84%B1-webview%EC%9D%B4%EC%9A%A9

[3] Android javascript bridge 연결,

https://jhappy.tistory.com/entry/android-자바스크립스-브릿지-연결하기-Javascript-bridge펌

[4] Android javascript 연결 심화, https://royzero.tistory.com/25

 

반응형