android - 如何将我的电容器插件导入 Ionic android 应用程序

标签 android ionic-framework capacitor

我需要在我的 Ionic 应用程序中执行一些 android native 代码,所以我尝试创建一个支持 android 的电容器插件。我使用本指南在我的 Ionic 应用程序中添加了电容器:https://capacitor.ionicframework.com/docs/getting-started/with-ionic/ .我从本指南创建了一个插件:https://capacitor.ionicframework.com/docs/plugins/

这是我使用插件的代码:

// home.page.ts
import {Component} from '@angular/core';

import {Plugins} from '@capacitor/core';

@Component({
    selector: 'app-home',
    template: `
<ion-button (click)="onEchoBtnClick()">Submit</ion-button>
`
})
export class HomePage {

    src: string | undefined;

    constructor() {
    }

    onEchoBtnClick() {
        const {Echo} = Plugins;

        const echoPlugin = Echo;

        echoPlugin.echo({
            value: '333'
        }).then(res => {
            alert('ok ' + JSON.stringify(res));
        }).catch(err => {
            alert('err ' + err);
        });
    }

}


然后我构建 Ionic 应用程序:ionic build并运行:
npx cap copy
npx cap sync
npx cap open android

并在 Android Studio 中运行该项目。当我运行该项目时,我收到了错误:Cannot read property 'echo' of undefined .我认为这是因为我需要在 MainActivity 类中添加插件:
// Other imports...
import com.example.myapp.EchoPlugin;

public class MainActivity extends BridgeActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
      // Ex: add(TotallyAwesomePlugin.class);
      add(EchoPlugin.class);
    }});
  }
}

问题是我收到错误“包 com.example.myapp.EchoPlugin 不存在”。我的插件位于“/echo”目录中。 android 项目位于“/android”目录中。如何将 Echo 插件导入到 android 项目中?

最佳答案

我用这个 [https://capacitorjs.com/docs/android/custom-code][1]
在您的 com/example/myapp/中的这条路径 android/app/src/main/java 中,我在 MainActivity.java 的同一级别创建了我的 PluginClass
完美调用 customFunction!。
[1]:https://capacitorjs.com/docs/android/custom-code

关于android - 如何将我的电容器插件导入 Ionic android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58855286/

相关文章:

android - Cordova BluetoothLE 仅检测 mac 笔记本电脑而不检测其他设备?

css - VS2015-Cordova-Ionic-Angular-ngMap : map height defaults to 300px

angular - 错误 : Uncaught (in promise): PushNotifications does not have web implementation

android - 我的应用程序使用 Webview 时总是崩溃?

java - AsyncTask doInBackground 方法未调用

java - Android setOnClickListener 不起作用

android - 使用 MPAndroidChart 自定义 XAxis 标签

angularjs - 使用 Charts.js 的 Angular 图表中未显示系列详细信息

angular - 如何将第三方 javascript 库与 ionic4 和电容器一起使用?

firebase - 与 FCM 通知捆绑在一起的 PWA