js調(diào)用android本地java代碼
当在Android上使用WebView控件开发一个Web应用时,可以创建一个通过Javascript调用Android端java代码的接口。也就是可以通过Javascript代码来调用Android本地的java代码!
下面来说明一下这个接口的具体创建方法。
第一步:首先需要在Android侧的java代码中创建实现了具体功能的类。(注意:作为接口的方法必须要加@JavascriptInterface注解)比如:
1 public class WebAppInterface { 2 Context mContext; 3 4 /** Instantiate the interface and set the context */ 5 WebAppInterface(Context c) { 6 mContext = c; 7 } 8 9 /** Show a toast from the web page */10 @JavascriptInterface11 public void showToast(String toast) {12 Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();13 }14 }
在这个例子中, 第三步:使用第二步创建的接口。在Web页面的js代码中,可以条用angle对象的showToast方法来间接调用第一步中WebAppInterface类中的showToast方法。具体应用示例如下: 参考资料:android-sdk/docs/guide/webapps/webview.html1 <input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />2 3 <script type="text/javascript">4 function showAndroidToast(toast) {5 angle.showToast(toast);6 }7 </script>
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章