Reputation: 141
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
Reputation: 403
You can call a Native method from a JS Controller using a JS Interface bridge:
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