user8462556
user8462556

Reputation: 536

Ionic capacitor plugin not working for android

I am written a very simple plugin which get all the messages from android device and pack it to response. When I am using npm install ionic-capacitor-sms-access and trying to access messages it just call web method but not the android method. So its not working can someone help me here and tell me what went wrong? Here is my plugin https://www.npmjs.com/package/ionic-capacitor-sms-access

(Note: only the android folder)

Upvotes: 1

Views: 5884

Answers (2)

tobika
tobika

Reputation: 1327

When I started I head really trouble distinguishing the web and native plugin but finally I understand that they are completely separated.

I recommend to rename the exported web plugin object in your web.ts file and add Web in the name. For me this was also necessary in order to not have compile errors.

TS2308: Module './definitions' has already exported a member named 'YourPlugin'. Consider explicitly re-exporting to resolve the ambiguity.

If you want to use your web plugin you import and use it like:

import { YourWebPlugin } from 'YOUR_PLUGIN_NPM_PACKAGE';

YourWebPlugin.callSomething();

If you want to use the native plugin you import and use it like:

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

const { YourPlugin } = Plugins;
YourPlugin.callSomething();

Don't forget to expose your native plugin to your android app project where you use your custom plugin https://capacitor.ionicframework.com/docs/plugins/android#export-to-capacitor

Upvotes: 1

Cross
Cross

Reputation: 796

It works, there are two ways to achieve this.

Method 1 (from the official tutorial)

What you need to do is just to keep following that tutorial to the section of 'Custom JavaScript', where shows demonstrates how to use your plugin within your ionic/typescripts codes.

such as:


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

const { SuperGreatPlugin } = Plugins;

export class CustomSuperPlugin {
  constructor() {
  }
  customAwesomeness() {
    SuperGreatPlugin.awesome();
  }
}

Notes:

  1. the name of the plugin class, i.e. 'SuperGreatPlugin' must be same with your java class for the plugin.

Method 2 (javascript way)

You can also import your plugin from the npm package you published. But be aware of the first line of the generated definitions.ts, declare module "@capacitor/core". This means you have to find your plugin from the specific module, here it is 'Plugins' as other plugins usage.

The following is the method 2:

import { SuperGreatPlugin } from 'YOUR_PLUGIN_NPM_PACKAGE';

async pluginEcho() {
    await Plugins.SuperGreatPlugin.echo({value: 'bla bla bla'})
}

call the function pluginEcho() in your ionic page.

Upvotes: 1

Related Questions