从AngularJS控制器调用Android函数

Calling an Android function from AngularJS controller

本文关键字:Android 函数 调用 控制器 AngularJS      更新时间:2023-09-26

我有一个问题,需要一些帮助。我正试图通过在前端使用角度控制器来调用一个android功能,但我无法让它工作。

主要活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView)findViewById(R.id.activity_main_webview);
    mWebView.setWebViewClient(new CustomWebViewClient());
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new AngularJSInterface(this), "Android");
    mWebView.loadUrl("http://192.168.70.101:3000/");
}

AngularJS接口:

public class AngularJSInterface {
Context mContext;
AngularJSInterface(Context c) {
    mContext = c;
}
public void showToast(String toast) {
    Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}

}

角度控制器:

angular.module('app').controller('ComplaintCtrl', function ($scope, $http, complaintService) {
    $scope.showToast = function(toast) {
        Android.showToast(toast);
        console.log("toast");
}

});

HTML:

<button label="toast" ng-click="showToast('Visar toast från angularJS')">toast</button>

控制台错误:

ReferenceError: Android is not defined
at Scope.$scope.showToast (http://localhost:3000/scripts/controllers/addcomplaint.js:34:3)
at http://localhost:3000/bower_components/angular/angular.js:10567:21
at http://localhost:3000/bower_components/angular-touch/angular-touch.js:438:9
at Scope.$eval (http://localhost:3000/bower_components/angular/angular.js:12412:28)
at Scope.$apply (http://localhost:3000/bower_components/angular/angular.js:12510:23)
at HTMLButtonElement.<anonymous> (http://localhost:3000/bower_components/angular-touch/angular-touch.js:437:13)
at HTMLButtonElement.jQuery.event.dispatch (http://localhost:3000/bower_components/jquery/dist/jquery.js:4409:9)
at HTMLButtonElement.elemData.handle (http://localhost:3000/bower_components/jquery/dist/jquery.js:4095:28) 

这是我第一次使用这种东西,我不太确定该怎么做。我试过通过谷歌搜索来寻找答案,但没有成功。我做错了什么?

将toast函数更改为static并直接调用它,或者先实例化它。并且,您没有名为Android的类,而是创建了AngularJSInterface。将Android.showToast更改为AngularJSInterface.showToast(如果使用静态)。