更新记录

1.0.1(2026-03-15) 下载此版本

1.0.0(2025-03-15)

新增功能

  • 支持 Android 平台保活
    • 前台服务通知 (ForegroundService Notification)
    • WakeLock 电源锁
    • 心跳机制
    • 电池优化白名单引导
  • 支持 iOS 平台保活
    • 后台任务 (BackgroundTask)
    • 后台音频保活
    • 后台定位保活
    • 心跳机制
  • 提供完整 API 接口
    • startKeepAlive - 启动保活
    • stopKeepAlive - 停止保活
    • checkKeepAliveStatus - 检查保活状态
    • setForegroundNotification - 设置前台服务通知
    • registerBackgroundTask - 注册后台任务
    • cancelBackgroundTask - 取消后台任务

技术实现

  • Android 端使用 UTS 插件实现
    • 创建通知渠道 (NotificationChannel)
    • 构建并显示常驻通知
    • WakeLock 电源锁管理
    • 自动引导用户设置电池优化白名单
  • iOS 端使用 UTS 插件实现
    • 后台任务管理
    • 后台模式配置

配置文件

  • Android: 内置 AndroidManifest.xml 权限配置
  • iOS: 内置 Info.plist 后台模式配置

兼容性

  • Android: API 21+ (Android 5.0+)
  • iOS: iOS 12+
  • HBuilderX: 3.6.8+
  • uni-app x: 5.03+

注意事项

  • Android 13+ 需要动态申请 POST_NOTIFICATIONS 权限
  • iOS 后台任务有时间限制
  • 不同厂商 ROM 对后台限制策略不同

1.0.0(2026-03-15) 下载此版本

新增功能

  • 支持 Android 平台保活
    • 前台服务 (ForegroundService)
    • WakeLock 电源锁
    • 心跳机制
    • 电池优化白名单引导
  • 支持 iOS 平台保活
    • 后台任务 (BackgroundTask)
    • 后台音频保活
    • 后台定位保活
    • 心跳机制
  • 提供完整 API 接口
    • startKeepAlive - 启动保活
    • stopKeepAlive - 停止保活
    • checkKeepAliveStatus - 检查保活状态
    • setForegroundNotification - 设置前台服务通知
    • registerBackgroundTask - 注册后台任务
    • cancelBackgroundTask - 取消后台任务

兼容性

  • Android: API 21+ (Android 5.0+)
  • iOS: iOS 12+
  • HBuilderX: 3.6.8+
  • uni-app: 3.1.0+

平台兼容性

uni-app(5.03)

Vue2 Vue3 Vue3插件版本 Chrome Safari app-vue app-nvue Android iOS 鸿蒙
- 1.0.0 - - - - - - -
微信小程序 支付宝小程序 抖音小程序 百度小程序 快手小程序 京东小程序 鸿蒙元服务 QQ小程序 飞书小程序 小红书小程序 快应用-华为 快应用-联盟
- - - - - - - - - - - -

uni-app x(5.03)

Chrome Safari Android iOS 鸿蒙 微信小程序
- - - -

cy-Keepalive 应用保活插件

插件简介

cy-Keepalive 是一款专为 UniApp 应用设计的保活插件,支持 Android 和 iOS 双平台。该插件通过多种保活策略确保应用在后台持续运行,防止系统自动终止进程,维持关键服务的稳定运行。

平台支持

平台 支持情况
Android ✅ 支持 (API 21+)
iOS ✅ 支持 (iOS 12+)
Harmony ❌ 暂不支持
Web ❌ 不支持
小程序 ❌ 不支持

安装方式

  1. uni_modules/cy-Keepalive 目录复制到项目的 uni_modules 目录下
  2. 在 HBuilderX 中重新编译项目

保活策略说明

Android 平台

策略 说明
ForegroundService 前台服务,显示常驻通知,最高优先级保活
WakeLock 电源锁,防止CPU休眠
Heartbeat 心跳机制,定期唤醒应用
电池优化白名单 引导用户将应用加入电池优化白名单

iOS 平台

策略 说明
BackgroundTask 后台任务,iOS提供的后台执行时间
BackgroundAudio 后台音频,播放静音音频保持后台运行
BackgroundLocation 后台定位,通过定位服务保持后台运行
Heartbeat 心跳机制,定期唤醒应用

API 文档

1. startKeepAlive - 启动保活

启动应用保活服务。

import { startKeepAlive } from '@/uni_modules/cy-Keepalive'

startKeepAlive({
  // Android 配置
  foregroundService: true,           // 是否启用前台服务通知
  notificationTitle: '应用运行中',    // 通知标题
  notificationContent: '应用正在后台运行', // 通知内容

  // iOS 配置
  backgroundAudio: true,             // 是否启用后台音频保活
  backgroundLocation: false,         // 是否启用后台定位保活

  // 通用配置
  heartbeatInterval: 60000,         // 心跳间隔(毫秒)

  success: (res) => {
    console.log('保活启动成功:', res)
    // res: { success: true, message: string, status: {...} }
  },
  fail: (err) => {
    console.error('保活启动失败:', err)
    // err: { errCode: number, errMsg: string }
  },
  complete: (res) => {
    console.log('操作完成:', res)
  }
})

2. stopKeepAlive - 停止保活

停止应用保活服务。

import { stopKeepAlive } from '@/uni_modules/cy-Keepalive'

stopKeepAlive({
  success: (res) => {
    console.log('保活已停止:', res)
  },
  fail: (err) => {
    console.error('停止失败:', err)
  }
})

3. checkKeepAliveStatus - 检查保活状态

获取当前保活服务的运行状态。

import { checkKeepAliveStatus } from '@/uni_modules/cy-Keepalive'

const status = checkKeepAliveStatus()
console.log('保活状态:', status)
// 返回值:
// {
//   isRunning: boolean,      // 是否正在保活
//   runningTime: number,     // 保活运行时间(毫秒)
//   keepAliveType: string,   // 保活类型 (如: "ForegroundService,WakeLock,Heartbeat")
//   processId: number        // 进程ID
// }

4. setForegroundNotification - 设置前台服务通知 (仅Android)

更新前台服务通知的内容。

import { setForegroundNotification } from '@/uni_modules/cy-Keepalive'

setForegroundNotification({
  title: '新标题',
  content: '新内容',
  success: (res) => {
    console.log('通知更新成功:', res)
  },
  fail: (err) => {
    console.error('通知更新失败:', err)
  }
})

5. registerBackgroundTask - 注册后台任务

注册一个后台任务。

import { registerBackgroundTask } from '@/uni_modules/cy-Keepalive'

registerBackgroundTask({
  taskName: 'myTask',
  success: (res) => {
    console.log('任务注册成功:', res)
  }
})

6. cancelBackgroundTask - 取消后台任务

取消已注册的后台任务。

import { cancelBackgroundTask } from '@/uni_modules/cy-Keepalive'

cancelBackgroundTask('myTask')

完整使用示例

<template>
  <view class="container">
    <view class="status-card">
      <text class="title">保活状态</text>
      <text class="status">{{ status.isRunning ? '运行中' : '已停止' }}</text>
      <text class="info">保活类型: {{ status.keepAliveType || '无' }}</text>
      <text class="info">运行时间: {{ formatTime(status.runningTime) }}</text>
      <text class="info">进程ID: {{ status.processId }}</text>
    </view>

    <view class="btn-group">
      <button type="primary" @click="startKeepAlive">启动保活</button>
      <button type="warn" @click="stopKeepAlive">停止保活</button>
      <button @click="checkStatus">检查状态</button>
    </view>
  </view>
</template>

<script>
import { startKeepAlive, stopKeepAlive, checkKeepAliveStatus } from '@/uni_modules/cy-Keepalive'

export default {
  data() {
    return {
      status: {
        isRunning: false,
        runningTime: 0,
        keepAliveType: '',
        processId: 0
      }
    }
  },

  onLoad() {
    this.checkStatus()
  },

  methods: {
    startKeepAlive() {
      // #ifdef APP-PLUS
      startKeepAlive({
        foregroundService: true,
        notificationTitle: '我的应用',
        notificationContent: '应用正在后台运行,点击返回',
        backgroundAudio: true,
        heartbeatInterval: 60000,
        success: (res) => {
          console.log('保活启动成功:', res)
          this.checkStatus()
          uni.showToast({
            title: '保活启动成功',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.error('保活启动失败:', err)
          uni.showToast({
            title: '启动失败',
            icon: 'none'
          })
        }
      })
      // #endif

      // #ifndef APP-PLUS
      uni.showToast({
        title: '仅支持App端',
        icon: 'none'
      })
      // #endif
    },

    stopKeepAlive() {
      // #ifdef APP-PLUS
      stopKeepAlive({
        success: (res) => {
          console.log('保活已停止')
          this.checkStatus()
          uni.showToast({
            title: '保活已停止',
            icon: 'success'
          })
        }
      })
      // #endif
    },

    checkStatus() {
      // #ifdef APP-PLUS
      this.status = checkKeepAliveStatus()
      // #endif
    },

    formatTime(ms) {
      if (!ms) return '0秒'
      const seconds = Math.floor(ms / 1000)
      const minutes = Math.floor(seconds / 60)
      const hours = Math.floor(minutes / 60)

      if (hours > 0) {
        return `${hours}小时${minutes % 60}分钟`
      } else if (minutes > 0) {
        return `${minutes}分钟${seconds % 60}秒`
      } else {
        return `${seconds}秒`
      }
    }
  }
}
</script>

<style>
.container {
  padding: 20px;
}

.status-card {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.status {
  font-size: 24px;
  color: #007AFF;
  margin-bottom: 10px;
}

.info {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.btn-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}
</style>

权限配置

Android 权限

插件已内置必要的权限配置在 AndroidManifest.xml 中:

  • FOREGROUND_SERVICE - 前台服务权限
  • FOREGROUND_SERVICE_SPECIAL_USE - 特殊前台服务权限
  • WAKE_LOCK - 电源锁权限
  • REQUEST_IGNORE_BATTERY_OPTIMIZATIONS - 请求忽略电池优化权限
  • RECEIVE_BOOT_COMPLETED - 开机自启动权限
  • POST_NOTIFICATIONS - 通知权限 (Android 13+)

在项目 manifest.json 中添加权限(可选,插件已内置):

{
  "app-plus": {
    "distribute": {
      "android": {
        "permissions": [
          "<uses-permission android:name=\"android.permission.FOREGROUND_SERVICE\"/>",
          "<uses-permission android:name=\"android.permission.FOREGROUND_SERVICE_SPECIAL_USE\"/>",
          "<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
          "<uses-permission android:name=\"android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS\"/>",
          "<uses-permission android:name=\"android.permission.RECEIVE_BOOT_COMPLETED\"/>",
          "<uses-permission android:name=\"android.permission.POST_NOTIFICATIONS\"/>"
        ]
      }
    }
  }
}

iOS 配置

插件已内置后台模式配置在 Info.plist 中:

  • audio - 后台音频
  • location - 后台定位
  • fetch - 后台获取
  • processing - 后台处理

在项目 manifest.json 中添加后台模式配置(可选,插件已内置):

{
  "app-plus": {
    "distribute": {
      "ios": {
        "UIBackgroundModes": ["audio", "location", "fetch", "processing"],
        "privacyDescription": {
          "NSLocationAlwaysUsageDescription": "应用需要后台定位权限以保持后台运行",
          "NSLocationAlwaysAndWhenInUseUsageDescription": "应用需要后台定位权限以保持后台运行",
          "NSLocationWhenInUseUsageDescription": "应用需要定位权限以保持后台运行",
          "NSMicrophoneUsageDescription": "应用需要麦克风权限以保持后台运行"
        }
      }
    }
  }
}

常见问题

Q1: Android 13+ 通知不显示?

A: Android 13 (API 33) 及以上版本需要动态申请通知权限。请在启动保活前申请权限:

// #ifdef APP-PLUS
if (uni.getSystemInfoSync().platform === 'android') {
  const systemInfo = uni.getSystemInfoSync()
  // Android 13+ 需要申请通知权限
  if (systemInfo.system && parseInt(systemInfo.system.replace('Android ', '')) >= 13) {
    uni.requestPermission({
      permissions: ['android.permission.POST_NOTIFICATIONS'],
      success: () => {
        // 权限获取成功后再启动保活
        this.startKeepAlive()
      },
      fail: () => {
        uni.showToast({
          title: '需要通知权限才能显示通知',
          icon: 'none'
        })
      }
    })
  } else {
    this.startKeepAlive()
  }
}
// #endif

Q2: iOS 后台运行一段时间后仍被终止?

A: iOS 对后台任务有严格限制,建议:

  1. 开启后台音频保活 (backgroundAudio: true)
  2. 在 Info.plist 中正确配置 UIBackgroundModes(插件已内置)
  3. 引导用户关闭应用的"后台应用刷新"限制

Q3: 如何引导用户加入电池优化白名单?

A: 插件会自动引导用户跳转到电池优化设置页面。在 Android 6.0+ 系统上,插件会自动检测并提示用户将应用加入白名单。

Q4: 保活会影响电池续航吗?

A: 会有一定影响,建议:

  1. 合理设置心跳间隔(建议60秒以上)
  2. 仅在必要时启动保活
  3. 不需要时及时停止保活

Q5: 小程序能使用保活吗?

A: 小程序平台不支持保活功能,这是平台限制。

Q6: 应用启动时自动开启保活怎么做?

A: 可以在 App.vueonLaunch 生命周期中调用 startKeepAlive

注意事项

  1. 合规使用: 请确保保活功能符合应用商店审核规范,避免滥用
  2. 用户知情: 使用保活功能时应告知用户,并在设置中提供关闭选项
  3. 资源消耗: 保活会消耗额外的系统资源,请合理使用
  4. 系统限制: 不同厂商ROM对后台限制策略不同,保活效果可能有所差异
  5. iOS限制: iOS对后台任务限制严格,保活时间有限
  6. 权限授予: Android 13+ 需要用户手动授予通知权限

更新日志

v1.0.0

  • 初始版本发布
  • 支持 Android/iOS 双平台保活
  • 实现前台服务通知、WakeLock电源锁等保活策略
  • 提供完整API接口
  • 自动引导用户设置电池优化白名单

技术支持

如有问题,请提交 Issue 或联系开发者。

隐私、权限声明

1. 本插件需要申请的系统权限列表:

需要后台运行权限、定位权限(可选)、通知权限(Android)

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

许可协议

MIT协议

暂无用户评论。