PREP WebView Part 2 - JavaScript Interface

Manifest

uses-permission android:name="android.permission.INTERNET"/>
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Layout

<?xml version="1.0" encoding="utf-8"?>
LinearLayout
xmlns:android="
android:orientation="vertical"
xmlns:tools="
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="matos.csu.prepwebview2.MainActivity"
<TextView
android:id="@+id/txtMsg"
android:background="#ffff00"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true" />
</LinearLayout

App Righ-click > New > Folder > Assets folder

Paste there: my_local_page1.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
html
head
title>Android GetPhone Demo</title
script language="javascript"
function setPerson(nameValue) { // move nameValue to input box – reset phone
document.getElementById("guiName").value = nameValue ;
document.getElementById("guiPhone").value = "" ;
}
functionaskAndroidToFindPhone() {
// call Android, ask it to find the person’s phone number
var person = document.getElementById("guiName").value;
HtmlAndroidBridge.showToast('Android is busy - Searching phones... '
+ person);
document.getElementById("guiPhone").value =
HtmlAndroidBridge.getPhoneNumber(person);
}
</script
style type="text/css"
.style1 {
color: #008000;
background:orange
font-family: Arial, Helvetica, sans-serif;
}
</style
</head
body
<h1 class="style1">Dos Amigos: HTML and Android</h1
<pa onClick="setPerson('Jose Cuervo')"
<u> Click here to set name to 'Jose Cuervo'</u</a
<pa onClick="setPerson('Waldo')"
<u> Click here to set name to 'Waldo'</u</a
<p>or just type any person's name
<p> Person's name <input type="text" id="guiName" />
<pinput type="button" onclick= "askAndroidToFindPhone()"
value="Ask Android to Find Person's Phone Number"
<p> Phone Number <input type="text" id="guiPhone" />
</body
</html

MainActivity.java

public class MainActivityextends AppCompatActivity {
private static final intMY_PERMISSIONS_REQUEST_READ_EXTERNAL = 123;
@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
askExplicitPermissions();
WebViewwebview = (WebView) findViewById(R.id.webView1);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new CustomJavaScriptInterface(this),
"HtmlAndroidBridge");
// if the HTML file is in the app's memory space use:
webview.loadUrl("file:///android_asset/my_local_page1.html");
// if the HTML files are stored in the SD card, use:
// webview.loadUrl("file:///sdcard/my_local_webpage1.html");
// CAUTION: Manifest must include
// <uses-permission android:name="android.permission.INTERNET"/>
// <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
}//onCreate
private void askExplicitPermissions() {
//if we already have permission to use the external SD card then do nothing!
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)
return;
// CAUTION: We DO NOT have the necessary permissions
// Should an explanation be given to the user regarding usage of external SD card?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an ASYNCHRONOUS explanation to the user, this thread will continue
// cancel app if user doesn't allow reading from SD card
Toast.makeText(this, "Explanation...", Toast.LENGTH_LONG).show();
}
// request the permission to use SD card.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL);
}
// /////////////////////////////////////////////////////////////////////////////////////////
@Override
public void onRequestPermissionsResult(intrequestCode,
String permissions[],
int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length0
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted - call onCreate again to setup any pending widgets
onCreate(null);
} else {
// permission denied
}
return;
}
}
}//onRequestPermissionResult
}//class

CustomJavaScriptInterface class

public class CustomJavaScriptInterface {
private Context context;
CustomJavaScriptInterface(Context context) {
// remember the application's context
this.context= context;
}
@JavascriptInterface
public void showToast(String toastMsg) {
// instead of dull JavaScript alert() use flashy Toasts
Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
}
@JavascriptInterface
public String getPhoneNumber(String person) {
// accept a person's name and fake that you are
// searching the Android's Contacts Database
person = person.toLowerCase();
if (person.equals("josecuervo"))
return "555-1111";
else if (person.equals("waldo"))
return "555-2222";
else
return "555-3333";
}
}