Inder malviya
Inder malviya

Reputation: 141

Access android native code from Ionic

I have created my Android application Ionic but later on realized that i want to access some hardware from my android device which is possible with android native code, so is there any way that i can access the Android code from Ionic app (Apache Cordova) ?

Upvotes: 1

Views: 2812

Answers (1)

Sanket Mendon
Sanket Mendon

Reputation: 403

You can call a Native method from a JS Controller using a JS Interface bridge:

  1. Define a JavaScriptHandler class within your MainActivity and define a JavascriptInterface method within this class. This interface will now act as a bridge between your webview and native container.
  2. Add this Javascript Handler to your app webview.
  3. Define a method which you need to call from your Controller.

Below is the code for MainActivity which extends CordovaActivity:

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;
  }
}

Call this native method from your Javascript controller like this:

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

  $scope.deviceName = "";

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

You can use whichever name you like for the exposing the JavaScriptHandler in javascript. In my case, I have used "NativeCall".

Upvotes: 2

Related Questions