android - 从 Ionic 访问 android 本机代码
问题描述
我已经创建了我的 Android 应用程序 Ionic,但后来意识到我想从我的 android 设备访问一些硬件,这可以通过 android 本机代码实现,那么有什么方法可以从 Ionic 应用程序(Apache Cordova)访问 Android 代码?
解决方案
您可以使用 JS 接口桥从 JS 控制器调用 Native 方法:
- 在 MainActivity 中定义一个 JavaScriptHandler 类,并在该类中定义一个 JavascriptInterface 方法。这个界面现在将充当您的 webview 和本机容器之间的桥梁。
- 将此 Javascript 处理程序添加到您的应用程序 webview。
- 定义一个需要从控制器调用的方法。
下面是扩展 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”。
推荐阅读
- lxc - 主机局域网上的 LXC 容器
- google-cloud-platform - Google Cloud Identity API 组成员资格错误 403
- python - 如何将两个熊猫列混合到一个数据框中,第一列的第一个元素,第二列的第二个元素等等?
- java - SpringBoot: Attach json on POST request with params
- sql-server - sql中的当前行+上一行
- python - 如何修复 Visual Studio 代码中的 DLL 加载失败?
- python - 在 Bokeh 中绘制烛台和体积烛台
- codemagic - CodeMagic 没有 Mac 自动代码签名错误
- postgresql - PostgreSQL:在 UPSERT 上的唯一性约束之前检查约束验证
- sql - 计算同一行中的每月和十二个最后日期