【问题标题】:Ionic capacitor plugin not working for android离子电容器插件不适用于android
【发布时间】:2020-01-16 01:23:16
【问题描述】:
【问题讨论】:
标签:
android
ionic4
capacitor
【解决方案1】:
有效,有两种方法可以实现。
方法一(来自官方教程)
您需要做的只是继续遵循该教程到“自定义 JavaScript”部分,其中演示了如何在您的 ionic/typescripts 代码中使用您的插件。
如:
import { Plugins } from '@capacitor/core';
const { SuperGreatPlugin } = Plugins;
export class CustomSuperPlugin {
constructor() {
}
customAwesomeness() {
SuperGreatPlugin.awesome();
}
}
注意事项:
- 插件类的名称,即“SuperGreatPlugin”必须与插件的 Java 类相同。
方法2(javascript方式)
您也可以从您发布的 npm 包中导入您的插件。但请注意生成的 definitions.ts 的第一行 declare module "@capacitor/core"。这意味着您必须从特定模块中找到您的插件,这里是“插件”作为其他插件的使用。
以下是方法二:
import { SuperGreatPlugin } from 'YOUR_PLUGIN_NPM_PACKAGE';
async pluginEcho() {
await Plugins.SuperGreatPlugin.echo({value: 'bla bla bla'})
}
在您的 ionic 页面中调用函数 pluginEcho()。
【解决方案2】:
当我开始时,我真的很难区分网络插件和原生插件,但最后我明白它们是完全分开的。
我建议在您的 web.ts 文件中重命名导出的网络插件对象,并在名称中添加 Web。对我来说,这也是必要的,以免出现编译错误。
TS2308: Module './definitions' has already exported a member named 'YourPlugin'. Consider explicitly re-exporting to resolve the ambiguity.
如果你想使用你的网络插件,你可以像这样导入和使用它:
import { YourWebPlugin } from 'YOUR_PLUGIN_NPM_PACKAGE';
YourWebPlugin.callSomething();
如果您想使用您导入的本机插件并使用它:
import { Plugins } from '@capacitor/core';
const { YourPlugin } = Plugins;
YourPlugin.callSomething();
不要忘记将您的原生插件公开给您使用自定义插件的 android 应用项目
https://capacitor.ionicframework.com/docs/plugins/android#export-to-capacitor