Friday 26 September 2014

Run Android Java code from Web Page

Run Android Java code from Web Page



Run Android Java code from Webpage



Modify /assets/mypage.html to add two button to call JavascriptInterface in Android Java code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<title>My HTML</title>
</head>
<body>
<h1>MyHTML</h1>

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<script type="text/javascript">
 function showAndroidToast(toast) {
     AndroidFunction.showToast(toast);
 }
</script>

<input type="button" value="Open Dialog" onClick="openAndroidDialog()" />

<script type="text/javascript">
 function openAndroidDialog() {
     AndroidFunction.openAndroidDialog();
 }
</script>

</body>
</html>



Main code, to add our JavascriptInterface.
package com.exercise.AndroidHTML;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;

public class AndroidHTMLActivity extends Activity {

WebView myBrowser;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
     myBrowser = (WebView)findViewById(R.id.mybrowser);
     myBrowser.addJavascriptInterface(new MyJavaScriptInterface(this), "AndroidFunction");
  
     myBrowser.getSettings().setJavaScriptEnabled(true);
     myBrowser.loadUrl("file:///android_asset/mypage.html");

 }

public class MyJavaScriptInterface {
 Context mContext;

    MyJavaScriptInterface(Context c) {
        mContext = c;
    }

    public void showToast(String toast){
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
 
    public void openAndroidDialog(){
     AlertDialog.Builder myDialog
     = new AlertDialog.Builder(AndroidHTMLActivity.this);
     myDialog.setTitle("DANGER!");
     myDialog.setMessage("You can do what you want!");
     myDialog.setPositiveButton("ON", null);
     myDialog.show();
    }

}
}

No comments:

Donate