Vue+Capacitor项目集成@capacitor/push-notifications致模拟器崩溃
解决Vue+Capacitor集成Push Notifications崩溃问题
1. 修正权限请求时机
Capacitor插件需等待应用完全初始化后才能调用,直接在组件创建阶段执行可能触发崩溃。修改App.vue代码,在Capacitor的deviceready事件触发后再发起权限请求:
<script setup> import { onMounted } from 'vue'; import { PushNotifications } from '@capacitor/push-notifications'; import { Capacitor } from '@capacitor/core'; onMounted(() => { if (Capacitor.isNativePlatform()) { document.addEventListener('deviceready', async () => { try { const permissionResult = await PushNotifications.requestPermissions(); console.log('权限请求状态:', permissionResult); } catch (error) { console.error('权限请求失败:', error); } }, false); } }); </script>
2. 检查Firebase配置完整性
- 确认
google-services.json文件已放置在android/app目录下 - 验证Android项目的
build.gradle配置:- 项目根目录
build.gradle中添加Google服务插件依赖:dependencies { classpath 'com.google.gms:google-services:4.4.1' } - app模块
build.gradle末尾添加插件引用:apply plugin: 'com.google.gms.google-services'
- 项目根目录
3. 补充AndroidManifest.xml必要配置
在android/app/src/main/AndroidManifest.xml中添加推送相关权限与组件:
<!-- 基础权限 --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> <!-- Firebase推送接收器 --> <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND"> <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <action android:name="com.google.android.c2dm.intent.REGISTRATION" /> <category android:name="${applicationId}" /> </intent-filter> </receiver>
4. 验证模拟器环境
- 使用带Google Play服务的Android模拟器(推荐选择API 33及以上的Google Play镜像)
- 打开模拟器内的Google Play商店,确保Google Play服务已更新至最新版本
- 重启模拟器后重新运行项目
5. 清理并重建Android项目
在项目根目录执行以下命令,清除旧构建缓存并同步配置:
cd android ./gradlew clean cd .. npx cap sync android npx cap run android
内容的提问来源于stack exchange,提问作者tog22
相关产品推荐
相关产品推荐

