21

我可以从我的phonegap java脚本函数和android 2.2中使用java函数,但是相同的代码没有在API 17上运行。我应该怎么做才能从API 17中的java脚本调用本机java代码。

我在我的java文件中使用这个代码

 objCustomNativeAccess = new CustomNativeAccess(this, appView);
            appView.addJavascriptInterface(objCustomNativeAccess,
                    "CustomNativeAccess");
    super.loadUrl("file:///android_asset/www/index.html");

我的 CustomNativeAccess 课程是

public class CustomNativeAccess {
        private WebView mAppView;
        private DroidGap mGap;

        /**
         * Constructor
         * 
         * @param gap
         * @param view
         */
        public CustomNativeAccess(DroidGap gap, WebView view) {
            mAppView = view;
            mGap = gap;
        }

        /**
         * Get the device phone number
         * 
         * @return
         */
        public JSONObject login(String email, String password) {
            JSONObject object = new JSONObject();
                    object.put("Login_Status", login_status);
            object.put("date", dateString);
            return object;
        }

在我的java脚本中,我使用这一行来调用这个登录函数

 var value = window.CustomNativeAccess.login(email,pass);

所以使用这个我成功地在 api 2.2 上调用它但是当我在 api 17 上运行这个代码时它给了我错误

未捕获的类型错误:对象 [object Object] 在 file:///android_asset/www/index.html:81 处没有方法“登录”

我如何在 api 17 上使用它

4

4 回答 4

39

您在 API 17 上要做的就是用以下方式注释您的方法@JavascriptInterface

public class CustomNativeAccess {
   @JavascriptInterface

然后摆脱构造函数部分:

/*private WebView mAppView;
    private DroidGap mGap;
    public CustomNativeAccess(DroidGap gap, WebView view) {
        mAppView = view;
        mGap = gap;
    }
*/

还要确保在项目中导入 JavascriptInterface:

 import android.webkit.JavascriptInterface;

你可以在这里阅读更多内容: WebView Android

编辑:您必须在类中使用 @JavascriptInterface 注释您希望从 Javascript 访问的每个方法。

于 2013-05-16T13:12:50.133 回答
4

来自 Android 4.2 文档:

注意:如果您将 targetSdkVersion 设置为 17 或更高,则必须将@JavascriptInterface注释添加到您希望网页代码可用的任何方法(该方法也必须是 public)。如果您不提供注释,则在 Android 4.2 或更高版本上运行时,您的网页将无法访问该方法。

来源:Android WebView Doc(重点补充)

于 2013-11-07T09:23:40.867 回答
0

addJavascriptInterface我刚刚使用 API 17编写了 Web 应用程序,它运行良好。我不知道你的代码发生了什么。也许你可以试试这些:

确保添加:

WebSettings webSettings = appView.getSettings();
webSettings.setJavaScriptEnabled(true);

二、为什么使用super.loadUrl,而不是appView来加载html?

objCustomNativeAccess = new CustomNativeAccess(this, appView);
appView.addJavascriptInterface(objCustomNativeAccess, "CustomNativeAccess");
appView.loadUrl("file:///android_asset/www/index.html");
于 2013-05-03T07:50:57.937 回答
-1

解决方案:

  1. android:targetSdkVersion将清单文件中的降低到 16。
  2. 在 project.properties: 中将编译 api 级别更改为 17,target=android-17并将回调方法注释为@JavascriptInterface.
于 2014-09-16T20:53:55.337 回答