by using the WebView kotlin android (II)

  How to make paper records APP JS code and web pages to interact, how to perform simply means that APP code in a Web page. Below to execute code in a web page to open the dialpad and enter the phone number, for example describes how to implement.
  A set WebView allows it to perform js code.
  Second, add by calling the WebView addJavascriptInterface a js object to the use, after the addition is complete is equivalent to the window object adds a child object in js inside, such as addJavascriptInterface (obj, "app") , then we can be used directly inside js js method to the app. to access the object exposed.
  Third, do not forget to add a list of documents inside the app to call privileges, <uses-permission android: name = "android.permission.CALL_PHONE" />
  code is very simple, just a few lines of code to complete, attention is not perfect code.
  APP end:

1  class MainActivity: AppCompatActivity () {
 2      class JSObject (var ctx: Context) {// js exposed to class
 3          @JavascriptInterface // js method to get access to the class, add it in the way, I do not hell is known
 . 4          Fun Call (n-: String)
 . 5          {
 . 6              var = Intent the Intent (Intent.ACTION_DIAL) .setData (Uri.parse ( "Tel:" + n-));
 . 7              startActivity (CTX, Intent, null );
 . 8          }
 . 9      }
 10      the override the onCreate Fun (savedInstanceState:? the Bundle ) {
 . 11          Super .onCreate (savedInstanceState)
 12 is         Web var: = WebView WebView ( the this )
 13 is          the setContentView (Web)
 14          web.webViewClient = WebViewClient ()
 15          web.settings.setJavaScriptEnabled ( to true ); // set WebView allows it to perform js code
 16          web.loadUrl ( "File: / //android_asset/a.html " ) // this place using local resources
 17          web.addJavascriptInterface (JSObject ( the this )," App " ) // js exposed to an object App,
 18      }
 19 }

  Because learning is less than two days, a lot of things have little knowledge of the way to record how the package inside resources to APP, click on the android studio of file -> new -> Folder - > Assets Folder dialog box to select a path, the default, at this time the project file will have one assets folder, we a.html page file copied to this folder in the project in which it will automatically appear, and we can use this file, the file path is file: /// android_asset / + filename. I do not know there is no other way to add resources, assets not know the file name can change or not?
  a.html Code

<html>
<head>
    <title>测试网页</title>
</head>
<body>
hello
</body>
</html>
<script language="JavaScript">
    app.call("123456789");
</script>

Guess you like

Origin www.cnblogs.com/gushandujian/p/12583796.html