Android

안드로이드 웹뷰와 웹간 스크립트 호출(Bridge)

주피터0410 2021. 12. 16. 11:28

webview와 web과 Android Bridge를 이용하여 통신

기본폴더구조

* 인터넷접속 퍼미션 설정 (AndroidManifest.xml)

<uses-permission android:name="android.permission.INTERNET"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"

    android:theme="@style/Theme.WebViewBridge">
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

 

* 메인 액티비티 (MainActivity.java)

@SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
public class MainActivity extends AppCompatActivity {

    private WebView webView;
    TextView mTextView;
    private WebSettings settings;
    Button mButton;

    private final Handler handler = new Handler();
    SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

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

        webView = (WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("http://test.com");		// 웹뷰에 호출될 도메인

        // 브릿지 연결 : AndroidBridge는 클래스 이름 "HybridApp"는 웹의 function명
        webView.addJavascriptInterface(new AndroidBridge(), "HybridApp");
        mButton = (Button)findViewById(R.id.button);
        mTextView = (TextView)findViewById(R.id.textview);
		
        // app에서 버튼 호출시 웹 function 호출
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                long time = System.currentTimeMillis();
                webView.loadUrl("javascript:AndroidToSend('Android > Web 전송 = "+dayTime.format(new Date(time))+"')");
            }
        });
    }

    private class AndroidBridge {
    
    	// 웹에서 호출하는 메소드
        @JavascriptInterface
        public void sendMessage(final String arg) {
            handler.post(new Runnable() {
                public void run() {
                    mTextView.setText(arg);
                }
            });
        }
    }
}

 

* Android 메인 레이아웃 (activity_main.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:contexte=".WebViewActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Web 데이터 전송"
        android:textSize="18dp" />

    <TextView
        android:id="@+id/textview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Web에서 받은메세지 : " />

    <WebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        tools:ignore="WebViewLayout" />

</LinearLayout>

 

* http://test.com 웹페이지

<?
/**
* 웹뷰와 web과 Android Bridge를 이용하여 통신
*/
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <head>
        <script>
		// Android에서 web으로 호출되는 function
		function AndroidToSend(arg){
			document.getElementById('textFromApp').innerHTML = arg;
		}
           
		// Android 메소드 호출
		function WebToSend(){
			window.HybridApp.sendMessage("web > Android 전송 = "+new Date());
		}
        </script>
    </head>
    <body>
<hr/>
	<button onclick="WebToSend();">Android 데이터 전송</button>
	<p id="textFromApp">Android에서 받은 메세지 : </p>
    </body>
</html>

1. (안드로이드에서) WEB 데이터 전송 버튼 클릭시 : 웹페이지로 전달

2. (웹에서) Android 데이터 전송 버튼 클릭시 : 안드로이드로 전달