Jerald
Jerald

Reputation: 4048

How to import my capacitor plugin to Ionic android app

I need to execute some android native code in my Ionic application, so I try to create a capacitor plugin with android support. I added capacitor to my Ionic application using this guide: https://capacitor.ionicframework.com/docs/getting-started/with-ionic/. And I created a plugin from this guide: https://capacitor.ionicframework.com/docs/plugins/

Here is the code where I use my plugin:

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

}

Then I build Ionic app: ionic build and run:

npx cap copy
npx cap sync
npx cap open android

And run the project in Android Studio. When I run the project I'm getting the error: Cannot read property 'echo' of undefined. I think it happens because I need to add the plugin in MainActivity class:

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

The problem is that I get error "package com.example.myapp.EchoPlugin does not exist". My plugin is in "/echo" directory. The android project is in "/android" directory. How to import Echo plugin to the android project?

Upvotes: 4

Views: 3507

Answers (2)

Yorland
Yorland

Reputation: 21

I used this [https://capacitorjs.com/docs/android/custom-code][1]

In this path android/app/src/main/java in your com/example/myapp/, I created my PluginClass in the same level of my MainActivity.java

Works perfectly calling the customFunction!. [1]: https://capacitorjs.com/docs/android/custom-code

Upvotes: 1

Ausi&#224;s Armesto
Ausi&#224;s Armesto

Reputation: 311

I had the same problem, and I solved rebuilding the project from Android Studio so it gets the new compiled configuration of the plugin.

Go to the Android Studio Build Menu and click 'Make Project'

Upvotes: 0

Related Questions