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

Capacitor推送通知:Android点击通知无法启动APP求助

问题描述

应用处于关闭状态时,设备可正常接收推送通知,但点击通知无法启动应用,pushNotificationActionPerformed中定义的逻辑不执行;应用处于打开状态时,通知功能正常,pushNotificationReceived可正常监听。

我的代码

capacitor.config.js

PushNotifications: {
  "presentationOptions": ["badge", "sound", "alert"]
},

notification-app.service.ts

import { Injectable, NgZone } from '@angular/core';
import { Capacitor } from '@capacitor/core';
import { ActionPerformed, PushNotifications, PushNotificationSchema, Token } from '@capacitor/push-notifications';

import { INotificacaoApp } from '../interfaces/INotificacaoApp';

@Injectable({
  providedIn: 'root'
})
export class NotificationAppService {

  _dadosNotificacao: INotificacaoApp;

  constructor(
    private zone: NgZone,
  ) { }

  async setupFCM() {
    if (Capacitor.getPlatform() == 'web') {
      return;
    } else {
      try {
        let permStatus = await PushNotifications.checkPermissions();
        if (permStatus) {
          if (permStatus.receive === 'prompt') {
            let permStatus2 = await PushNotifications.requestPermissions();
            if (permStatus2) {
              if (permStatus2.receive !== 'granted') {
                console.log('Notification not granted')
                return;
              } else {
                await PushNotifications.register();
              }
            }
          } else {
            if (permStatus.receive !== 'granted') {
              console.log('Notification not granted')
              return;
            } else {
              await PushNotifications.register();
            }
          }
        }

        PushNotifications.addListener(
          'registration',
          async (token: Token) => {
            console.log('My token: ' + JSON.stringify(token));
          }
        );

        PushNotifications.addListener('registrationError', async (error: any) => {
          console.log('Error no registro do token de notificacao: ' + JSON.stringify(error));
        });

        PushNotifications.addListener(
          'pushNotificationReceived',
          async (notification: PushNotificationSchema) => {
            this.zone.run(() => {
              if (notification.data
                && notification.data.dados) {
                this._dadosNotificacao = JSON.parse(notification.data.dados) as INotificacaoApp;
                console.log('recebeu notificacao')
                console.log(this._dadosNotificacao)
              }
            });
          }
        );

        PushNotifications.addListener(
          'pushNotificationActionPerformed',
          async (notification: ActionPerformed) => {
            console.log('Action performed: ' + JSON.stringify(notification.notification));
          }
        );

      } catch (err) {
        console.log(`SetupFCM com erro`)
      }
    }
  }

  async RemoveListeners() {
    PushNotifications.removeAllListeners();
  }

}

setupFCM调用位置(tabs.page.ts)

constructor(
  private platform: Platform,
  private notificationAppService: NotificationAppService
) {
  this.platform.ready().then(async () => {
    this.notificationAppService.setupFCM();
  });
}

版本信息

  • npm: 9.1.1
  • node: 18.12.1
  • @capacitor/cli: 4.5.0
  • @capacitor/core: 4.5.0
  • @capacitor/android: 4.5.0
  • @capacitor/ios: 4.5.0
  • @capacitor/push-notifications: 4.1.2
  • @angular/core: 14.2.10
  • @ionic/angular: 6.3.7
  • @ionic/cli: 6.20.4

已尝试的配置调整

android/build.gradle添加google-services classpath

buildscript {
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.2'
        classpath 'com.google.gms:google-services:4.3.14'
    }
}

android/app/build.gradle添加插件及依赖

plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}
...
dependencies {
     ...
    implementation 'com.google.firebase:firebase-messaging:23.0.5'
}

variable.gradle添加firebaseMessagingVersion

ext {
    minSdkVersion = 22
    compileSdkVersion = 32
    targetSdkVersion = 32
    ...
    firebaseMessagingVersion = '23.0.5'
}

google-services.json已放置在android/app目录下。


解决方案

1. 提前注册推送监听,避免冷启动错过事件

将setupFCM调用移至app.component.ts的初始化方法中,确保应用冷启动时最先完成监听注册,不会错过通知点击事件:

import { Component } from '@angular/core';
import { Platform } from '@ionic/angular';
import { NotificationAppService } from './services/notification-app.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent {
  constructor(
    private platform: Platform,
    private notificationAppService: NotificationAppService
  ) {
    this.initializeApp();
  }

  async initializeApp() {
    await this.platform.ready();
    await this.notificationAppService.setupFCM();
  }
}

2. 修正推送Payload格式(Android端)

确保FCM推送Payload包含click_action字段,值为应用主Activity的完整类名(如com.yourpackage.app.MainActivity),同时保留data字段传递业务信息:

{
  "notification": {
    "title": "测试通知",
    "body": "点击打开应用"
  },
  "data": {
    "dados": "{\"id\":1,\"message\":\"测试数据\"}"
  },
  "click_action": "com.yourpackage.app.MainActivity",
  "to": "设备Token"
}

3. 调整AndroidManifest.xml配置

为主Activity添加launchMode="singleTop",并配置对应intent-filter捕获通知点击事件:

<activity
    android:name=".MainActivity"
    android:launchMode="singleTop"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
    android:hardwareAccelerated="true"
    android:theme="@style/AppTheme.NoActionBarLaunch">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="com.yourpackage.app.MAIN_ACTIVITY" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

注意action值需与Payload中的click_action保持一致。

4. 简化FCM初始化逻辑

去除冗余条件判断,确保监听注册代码在权限通过后必执行:

async setupFCM() {
  if (Capacitor.getPlatform() === 'web') return;

  try {
    let permStatus = await PushNotifications.checkPermissions();
    if (permStatus.receive === 'prompt') {
      permStatus = await PushNotifications.requestPermissions();
    }

    if (permStatus.receive !== 'granted') {
      console.log('Notification permission not granted');
      return;
    }

    await PushNotifications.register();

    PushNotifications.addListener('registration', (token: Token) => {
      console.log('Registration token:', JSON.stringify(token));
    });

    PushNotifications.addListener('registrationError', (error) => {
      console.error('Registration error:', JSON.stringify(error));
    });

    PushNotifications.addListener('pushNotificationReceived', (notification: PushNotificationSchema) => {
      this.zone.run(() => {
        if (notification.data?.dados) {
          this._dadosNotificacao = JSON.parse(notification.data.dados) as INotificacaoApp;
          console.log('Received notification:', this._dadosNotificacao);
        }
      });
    });

    PushNotifications.addListener('pushNotificationActionPerformed', (action: ActionPerformed) => {
      console.log('Notification action performed:', JSON.stringify(action.notification));
      this.zone.run(() => {
        if (action.notification.data?.dados) {
          const data = JSON.parse(action.notification.data.dados) as INotificacaoApp;
          // 这里添加你的业务逻辑,比如页面跳转
        }
      });
    });

  } catch (err) {
    console.error('FCM setup error:', err);
  }
}

5. 冷启动测试

完全关闭应用(从最近任务中移除),发送推送后点击通知,查看日志是否触发pushNotificationActionPerformed逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:30:47