Android

javascript to java interface on android

aucd29 2013. 10. 8. 14:43
[code]
<html>
<head>
<script language="JavaScript">
function callJS(arg) {
    document.getElementById('replaceme').innerHTML = arg;
}
</script>
</head>
<body>
<h1>WebView</h1>
<p><a href="#" onclick="window.alert('Alert from JavaScript')">Display JavaScript alert</a></p>
<p><a href="#" onclick="window.android.callAndroid('Hello from Browser')">Call Android from JavaScript</a></p>
<p id="replaceme"></p>
</body>
</html>
[/code]

[code]
package org.example.localbrowser;
...
public class LocalBrowser extends Activity {
    private static final String TAG = "LocalBrowser";
    private final Handler handler = new Handler();
    private WebView webView;
    private TextView textView;
    private Button button;

    /** Object exposed to JavaScript */
    private class AndroidBridge {
    
        public void callAndroid(final String arg) { // must be final
            handler.post(new Runnable() {
                public void run() {
                    Log.d(TAG, "callAndroid(" + arg + ")");
                    textView.setText(arg);
                }
            });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Find the Android controls on the screen
        webView = (WebView) findViewById(R.id.web_view);
        textView = (TextView) findViewById(R.id.text_view);
        button = (Button) findViewById(R.id.button);

        // Rest of onCreate follows...
        // Turn on JavaScript in the embedded browser
        webView.getSettings().setJavaScriptEnabled(true);

        // Expose a Java object to JavaScript in the browser
        webView.addJavascriptInterface(new AndroidBridge(), "android");

        // Set up a function to be called when JavaScript tries
        // to open an alert window
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(final WebView view, final String url, final String message, JsResult result) {
                Log.d(TAG, "onJsAlert(" + view + ", " + url + ", " + message + ", " + result + ")");
                Toast.makeText(LocalBrowser.this, message, 3000).show();
                result.confirm();

                return true; // I handled it
            }
        });
        
        // Load the web page from a local asset
        webView.loadUrl("file:///android_asset/index.html");

        // This function will be called when the user presses the
        // button on the Android side
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                Log.d(TAG, "onClick(" + view + ")");
                webView.loadUrl("javascript:callJS('Hello from Android')");
            }
        }
    }
}
[/code]

보안에 주의할 것....

내가 하는것도 아니고 귀찮아서 안 찾아보다가 검색하니 걍 나오는...