首页 > 解决方案 > 从 Ionic 访问 android 本机代码

问题描述

我已经创建了我的 Android 应用程序 Ionic,但后来意识到我想从我的 android 设备访问一些硬件,这可以通过 android 本机代码实现,那么有什么方法可以从 Ionic 应用程序(Apache Cordova)访问 Android 代码?

标签: androidcordovaionic-frameworkcross-platformcordova-plugins

解决方案


您可以使用 JS 接口桥从 JS 控制器调用 Native 方法:

  1. 在 MainActivity 中定义一个 JavaScriptHandler 类,并在该类中定义一个 JavascriptInterface 方法。这个界面现在将充当您的 webview 和本机容器之间的桥梁。
  2. 将此 Javascript 处理程序添加到您的应用程序 webview。
  3. 定义一个需要从控制器调用的方法。

下面是扩展 CordovaActivity 的 MainActivity 的代码:

public class MainActivity extends CordovaActivity {
  public static Context mContext;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = MainActivity.this;
    mLoader = new ProgressDialog(mContext);

    // enable Cordova apps to be started in the background
    Bundle extras = getIntent().getExtras();
    if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
      moveTaskToBack(true);
    }

    // Set by <content src="index.html" /> in config.xml
    loadUrl(launchUrl);

    final WebView webView = (WebView) appView.getEngine().getView();
    webView.addJavascriptInterface(this.getJavaScriptHandler(), "NativeCall");
  }

  public JavaScriptHandler getJavaScriptHandler() {
    return new JavaScriptHandler(this.getApplicationContext());
  }

  public class JavaScriptHandler {
    CordovaActivity parentActivity;
    private Context mContext;

    public JavaScriptHandler(final Context context) {
      this.mContext = context;
    }

    @JavascriptInterface
    public String mNativeFunction() {
      return getDeviceName;
    }   
  }

  public static String getDeviceName() {
    String brand = Build.BRAND;
    String manufacturer = Build.MANUFACTURER;
    String model = Build.MODEL;
    if (model.startsWith(brand)) {
      return (model);
    }
    return (brand) + " " + model;
  }
}

从您的 Javascript 控制器调用此本地方法,如下所示:

MyDemoApp.controller('SomePageController', function ($scope) {

  $scope.deviceName = "";

  $scope.getDeviceName = function () {
      $scope.deviceName = NativeCall.mNativeFunction();
  }
})

您可以使用任何您喜欢的名称来在 javascript 中公开 JavaScriptHandler。就我而言,我使用了“NativeCall”。


推荐阅读