[안드로이드] Webview Bridge 구현

변준영·2022년 12월 28일
1

Webview bridge란?[1]

  • Bridge(브릿지)란 Android와 WebView의 통신을 위해 만들어진 JavaScript용 Interface
  • Web에서 발생하는 이벤트에서 Android 동작(메서드)을 직접적으로 통제할 수 없음
    -> Bridge라는 통로를 통해 Web에서 Android 동작을 호출

=> Bridge는 WebView에 적용될 Interface 구현체이며, WebView는 객체의 메서드들을 인스턴스를 통해 호출할 수 있음

*코드는 이전 글에 이어서 사용

1. Web -> 안드로이드[2]

HTML 버튼 클릭시 Toast Message를 띄우는 기능 구현

MainActivity.java

  • URL을 테스트할 HTML로 변경
    private String myUrl = "file:///android_asset/testHTML.html";
  • onCreate()에 다음 추가

           // WebSettings
           WebSettings webSettings = myWebView.getSettings();
           webSettings.setJavaScriptEnabled(true); // javascript를 사용할 경우 다음과 같이 설정
    
           // JavascriptInterface 연결(bridge) :: Android
           myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
  • Toast Message 기능을 가진 WebAppInterface Class 추가
public class WebAppInterface {
        Context mContext;

        /**
         * Instantiate the interface and set the context
         */
        WebAppInterface(Context c) {
            mContext = c;
        }

        /**
         * Show a toast from the web page
         */
        @JavascriptInterface
        public void showToast(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
        }
    }

TestHTML.html

  • 간단한 버튼을 만들고, 클릭 시 WebAppInterface의 showToast()를 호출하는 기능을 구현
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
  </head>
  <body>
    <input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')"/>

    <script type="text/javascript">
      function showAndroidToast(toast) {
      	Android.showToast(toast); <!-- WebAppInterface의 showToast() 사용 -->
      }
    </script>
  </body>	
</html>

실행화면

  • 다음과 같이 버튼 클릭 시 정상적으로 Toast Message가 추가되는 것을 확인할 수 있다.

2. 안드로이드 -> Web [5]

Android 버튼 클릭시 Webview화면에 String 추가

activity_main.xml

  • 버튼추가
	<Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="addText"
    />

MainActivity.java

  • 전역변수 Button 및 String에 사용할 cnt 추가
private Button mBtn; // 버튼추가
private int cnt = 0; // webView로 넘길 count
  • onCreate()에 버튼 메소드 추가
// 버튼 클릭 구현
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myWebView.loadUrl("javascript:AndroidToSend('버튼 누른 횟수 = "+cnt+"회')");
                cnt++;
            }
        });

TestHTML.html

  • body에 text를 출력 할 "textFromApp"를 만들고, textFromApp에 메시지를 출력하는 function 생성
<body>
  ...
	<p id="textFromApp">Android에서 받은 메세지 : </p>
  ...
</body>
<script>
  ...
	function AndroidToSend(myString) {
            document.getElementById('textFromApp').innerHTML = myString;
        }
  ...
</script>

실행화면

  • 다음과 같이 버튼 클릭 시 정상적으로 화면에 버튼을 누를때마다 횟수가 늘어나는 것을 확인 할 수 있다.

참고

[1] https://devgeek.tistory.com/92
[2] https://developer.android.com/guide/webapps/webview?hl=ko#java
[3] https://black-jin0427.tistory.com/272
[4] https://ddolcat.tistory.com/593
[5] https://jupiter0410.tistory.com/9

코드 : https://github.com/jybyun9533/Android_Study/tree/master/WebView02

0개의 댓글