【问题标题】:How to copy file to /res/raw using cordova plugin hook如何使用cordova插件挂钩将文件复制到/res/raw
【发布时间】:2026-02-18 03:20:06
【问题描述】:

正如标题所示,我正在尝试为 android 构建一个 cordova 插件(这是一个空插件),其目的是将文件复制到 APK 的 /res/raw 文件夹中。 Android 似乎需要这样做,因此 OneSignal 可以在收到通知时播放自定义铃声。为了实现这一点,我使用了 after_plugin_install 和 before_build 的钩子。内容相同,不同的是文件夹。这个钩子是this one的修改版。

我为此使用插件而不是将资源添加到cordova 项目文件夹的原因是因为我无权访问cordova 项目文件夹。因此,我唯一的“解决方法”是使用插件(带有钩子)来做到这一点。

钩子文件的摘录:


// configure all the files to copy from each of the resource paths.
// key of object is the source file, value is the destination location.
// the directory/file structure used closely mirrors how the resources
// are stored in each platform
var androidFilesToCopy = {
  // android icons
  "android/beep.wav": "beep.wav"
};

// required node modules
var fs = require('fs');
var path = require('path');
var rootdir = "plugins";
var buildDir = "build";

// android platform resource path
var platformAndroidPath = 'locales/android/raw/';

我已经测试了 platformAndroidPath 的几个值和几个“挂钩时间线类型”(before_build、after_build、before_prepare 等),但似乎没有一个有效。我还看到,如果我使用“cordova plugins add location”(插件为复数形式),它会检测到文件。如果我使用“cordova plugin add location”(插件作为单数)它不会检测到文件。

此时我有点迷茫,真的不知道现在该去哪里。如果有人能够提供一些指导,那将不胜感激。完整的插件是here

谢谢!

【问题讨论】:

    标签: android cordova plugins hook


    【解决方案1】:

    根据您所针对的 cordova-android 版本,您要查找的路径会有所不同。

    例如cordova platform add android@6.4.0,这是整个文件夹结构:

    ├── hooks
    ├── platforms
    │   └── android
    │       ├── CordovaLib
    │       ├── assets
    │       ├── cordova
    │       ├── libs
    │       ├── platform_www
    │       ├── res # <- this is the path you want!
    │       └── src
    ├── plugins
    ├── res
    └── www
    

    请注意 res 就在“android”文件夹下,这就是 android 资源所在的位置。

    但是,对于cordova platform add android@8.0.0

    ├── hooks
    ├── platforms
    │   └── android
    │       ├── CordovaLib
    │       ├── app
    │       │   └── src
    │       │       └── main
    │       │           ├── assets
    │       │           ├── java
    │       │           ├── libs
    │       │           └── res # <- this is the path you want!
    │       ├── cordova
    │       └── platform_www
    ├── plugins
    ├── res
    └── www
    

    因此,在实践中,这取决于您运行钩子的 Cordova 平台,但通常是这样的:

    • cordova-android platforms/android/res/raw
    • cordova-android >= 7:platforms/android/app/src/main/res/raw

    你可以找到一个类似的例子here

    【讨论】: