Hello, here is sample code about how to send data from HTML/Javascript to native Android app using webview.
webview.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
mypage.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width; user-scalable=0;" /> <title>HTML Android</title> </head> <body> <h1>HTML Android</h1> <input type="button" value="Button 1" onClick="sendDataToAndroid('Button 1 is click')" /> <input type="button" value="Button 2" onClick="sendDataToAndroid('Button 2 is click')" /> function sendDataToAndroid(toast) { MyFunction.onButtonClick(toast); } </body> </html>
WebViewActivity.java
import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.widget.Toast; @SuppressLint({"NewApi", "SetJavaScriptEnabled"}) public class WebViewActivity extends Activity { WebView mWebViewDemo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview); mWebViewDemo = (WebView) findViewById(R.id.webview); ButtonClickJavascriptInterface myJavaScriptInterface = new ButtonClickJavascriptInterface(WebViewActivity.this); mWebViewDemo.addJavascriptInterface(myJavaScriptInterface, "MyFunction"); mWebViewDemo.getSettings().setJavaScriptEnabled(true); mWebViewDemo.loadUrl("file:///android_asset/mypage.html"); } public class ButtonClickJavascriptInterface { Context mContext; ButtonClickJavascriptInterface(Context c) { mContext = c; } @JavascriptInterface public void onButtonClick(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } } }
No hay comentarios:
Publicar un comentario