capacitor和capacitor官方插件项目源码解析
kelvin 发布于 2024-04-17

1、Capacitor源码

https://github.com/ionic-team/capacitor

在github上可以下载到capacitor框架的源码,下载后解压,可以查看主要的类,后面插件开发中经常引用的类

2、capacitor官方的插件源码capacitor-plugins

https://github.com/ionic-team/capacitor-plugins

可以在github上下载,(下载解压后为capacitor-plugins-main),每个插件文件夹主要有三个文件夹,android,ios和src,对应android,ios和web的实现,android使用java,ios使用swift,srcweb使用typescript语言。

1) 在src下的definitions.ts文件中定义插件的类型和方法等,例如获取设备信息的device插件,在src下definitions.ts中的定义如下

export interface DevicePlugin {
  /**
   * Return an unique identifier for the device.
   *
   * @since 1.0.0
   */
  getId(): Promise<DeviceId>;

  /**
   * Return information about the underlying device/os/platform.
   *
   * @since 1.0.0
   */
  getInfo(): Promise<DeviceInfo>;

  /**
   * Return information about the battery.
   *
   * @since 1.0.0
   */
  getBatteryInfo(): Promise<BatteryInfo>;

  /**
   * Get the device's current language locale code.
   *
   * @since 1.0.0
   */
  getLanguageCode(): Promise<GetLanguageCodeResult>;

  /**
   * Get the device's current language locale tag.
   *
   * @since 4.0.0
   */
  getLanguageTag(): Promise<LanguageTag>;
}

web.ts中是web端的具体实现,例如device插件的web端实现,所有的插件web端都extends WebPlugin

export class DeviceWeb extends WebPlugin implements DevicePlugin

 

2) android

android文件夹中在device\android\src\main\java\com\capacitorjs\plugins\device\DevicePlugin.java文件中对应的实现,

@CapacitorPlugin(name = "Device")

public class DevicePlugin extends Plugin 

主要使用@CapacitorPlugin注解,name表示插件名称,例如在ionic中使用插件,则引用import { Device } from '@capacitor/device';

,在definitions.ts中的定义的方法,在android的实现对应的方法名,且前面加上 @PluginMethod注解

   @PluginMethod

    public void getId(PluginCall call) {

3) ios,capacitor源码中ios中的主要类型

在插件中

kelvin
关注 私信
文章
92
关注
0
粉丝
0