You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cordova 9 Android:应用后台或锁屏时如何保持振动?

Android后台/熄屏时保持振动的解决方案

嘿,这个问题我之前帮开发者解决过不少次——Android系统为了省电,会在Web应用(包括普通网页和PWA)进入后台或熄屏时暂停主线程的执行,这就是navigator.vibrate()会中途停止的核心原因。下面给你两种针对性的解决方案,看你属于哪种场景:

场景1:你用WebView封装了原生Android应用(最可靠)

这是实现后台熄屏振动的最优方案,因为可以借助Android原生的前台Service来突破浏览器的限制——前台Service在Android 8.0+系统中不会轻易被后台杀死,能稳定执行振动逻辑。

步骤1:添加必要权限

在AndroidManifest.xml中声明振动和前台Service权限:

<uses-permission android:name="android.permission.VIBRATE" />
<!-- Android 8.0+ 必须的前台Service权限 -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

步骤2:创建前台振动Service

写一个处理振动的Service类(以Kotlin为例):

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.os.Vibrator
import android.os.VibrationEffect

class BackgroundVibrationService : Service() {
    private lateinit var vibrator: Vibrator

    override fun onCreate() {
        super.onCreate()
        vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        
        // Android 8.0+ 需要创建通知渠道并启动前台Service
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "vibration_channel",
                "后台振动服务",
                NotificationManager.IMPORTANCE_LOW
            )
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
            
            val notification = Notification.Builder(this, "vibration_channel")
                .setContentTitle("振动中")
                .setSmallIcon(R.drawable.ic_notification) // 替换成你的通知图标
                .build()
            startForeground(1, notification)
        }
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val duration = intent?.getLongExtra("vibration_duration", 5000) ?: 5000
        
        // 根据Android版本选择振动方式
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val effect = VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE)
            vibrator.vibrate(effect)
        } else {
            vibrator.vibrate(duration)
        }
        return START_STICKY // 确保Service被杀死后能重启
    }

    override fun onBind(intent: Intent): IBinder? = null
}

步骤3:让Web端调用原生Service

在WebView初始化时注入JavaScript接口,让网页可以触发后台振动:

webView.settings.javaScriptEnabled = true
webView.addJavascriptInterface(object {
    @JavascriptInterface
    fun startBackgroundVibration(duration: Long) {
        val intent = Intent(applicationContext, BackgroundVibrationService::class.java)
        intent.putExtra("vibration_duration", duration)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent)
        } else {
            startService(intent)
        }
    }
}, "AndroidVibrator")

步骤4:Web端调用代码

在你的网页中,替换原来的navigator.vibrate()为这个原生调用:

// 调用后台振动,持续5秒
window.AndroidVibrator.startBackgroundVibration(5000);

场景2:你是纯PWA/普通网页(限制较多)

纯Web应用在Android后台熄屏时,浏览器会严格限制主线程和Worker的运行,navigator.vibrate()几乎无法持续执行。这里有个折中的思路:

  • 引导用户将PWA添加到主屏幕(变成Trusted Web Activity,本质是WebView封装),然后按照上面的原生方案实现。
  • 如果必须纯Web,只能尝试使用Wake Lock API暂时保持屏幕唤醒,但这不符合你“屏幕熄灭”的需求,所以不推荐。

关键提醒

  • 前台Service会显示一个低优先级通知,这是Android系统的强制要求,无法隐藏(除非你的应用是系统应用)。
  • 长时间振动可能会被系统判定为恶意行为,建议合理控制振动时长和频率。

内容的提问来源于stack exchange,提问作者Persson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:37:53