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

Angular + Firebase Cloud Messaging(FCM) + Cordova(安卓):如何实现FCM注册?

Hey there! Let’s work through fixing the FCM registration issue for your Angular 5 + Cordova Android app. I’ve tackled similar setups before, so here’s a practical, step-by-step guide to get this sorted:

1. Make Sure You’re Using the Right Cordova FCM Plugin

The web-based Firebase/AngularFire setup won’t work for Cordova—you need a Cordova-specific FCM plugin. The most reliable one these days is cordova-plugin-fcm-with-dependecy-updated, which handles modern FCM requirements automatically. Run these commands to set it up:

# Remove any conflicting old Firebase plugins first (if you have them)
cordova plugin remove cordova-plugin-firebase

# Install the updated FCM plugin
cordova plugin add cordova-plugin-fcm-with-dependecy-updated
2. Configure Firebase Credentials for Android

You already have a Firebase project, so download the google-services.json file from your Firebase console (under Android app settings). Place this file in your Cordova project’s platforms/android/app/ directory, then add this to your config.xml to ensure it’s included in the build:

<platform name="android">
  <resource-file src="google-services.json" target="app/google-services.json" />
  <!-- Keep your existing Android config here -->
</platform>

The plugin should automatically add the Google Services Gradle dependencies, but if you run into build errors, double-check that platforms/android/build.gradle includes this in the dependencies block:

classpath 'com.google.gms:google-services:4.3.10'

And that platforms/android/app/build.gradle has this line at the very end:

apply plugin: 'com.google.gms.google-services'
3. Adjust Your Angular Code for Cordova’s Environment

Cordova plugins only work after the deviceready event fires—this is a critical detail that’s easy to miss! Update your FCM service to wait for this event before initializing:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Declare the global FCMPlugin variable provided by the Cordova plugin
declare var FCMPlugin: any;

@Injectable()
export class FcmRegistrationService {
  constructor(private http: HttpClient) {}

  initFcmRegistration() {
    // Wait for Cordova to be fully ready
    document.addEventListener('deviceready', () => {
      // Request notification permission from the user
      FCMPlugin.requestPermission((permissionStatus) => {
        if (permissionStatus === 'granted') {
          // Fetch the FCM token
          FCMPlugin.getToken((token) => {
            console.log('Successfully retrieved FCM token:', token);
            // Send the token to your backend API
            this.postTokenToBackend(token);
          }, (error) => {
            console.error('Failed to get FCM token:', error);
          });

          // Listen for token refreshes (tokens can change over time)
          FCMPlugin.onTokenRefresh((newToken) => {
            console.log('FCM token refreshed:', newToken);
            this.postTokenToBackend(newToken);
          });
        } else {
          console.warn('User denied notification permission');
        }
      }, (error) => {
        console.error('Error requesting notification permission:', error);
      });
    }, false);
  }

  private postTokenToBackend(token: string) {
    // Replace with your actual API endpoint
    this.http.post('/api/fcm/store-token', { token: token })
      .subscribe(
        response => console.log('Token sent to backend successfully'),
        error => console.error('Failed to send token to backend:', error)
      );
  }
}

Then call initFcmRegistration() from your AppComponent’s ngOnInit method to kick off the process when the app loads.

4. Fix Android-Specific Edge Cases
  • Check SDK Versions: Ensure your Android min/target SDK versions meet the plugin’s requirements. Add these to config.xml:
    <preference name="android-minSdkVersion" value="21" />
    <preference name="android-targetSdkVersion" value="33" />
    
  • Verify Package Name: Make sure the package ID in your config.xml (the id attribute in <widget>) matches exactly what you registered in Firebase for your Android app.
  • Test on a Real Device: Emulators often lack Google Play Services, which are required for FCM. Use a physical Android device for testing.
5. Test the Flow End-to-End
  1. Build the Android APK: cordova build android
  2. Install it on your device: cordova run android
  3. Check the Logcat logs (use Android Studio or adb logcat) for lines like "Successfully retrieved FCM token" to confirm registration worked.
  4. Verify your backend receives the token, then send a test notification to make sure it arrives on the device.

If you still hit issues, check these quick fixes:

  • Run cordova plugin list to confirm the FCM plugin is installed correctly.
  • Look for Firebase initialization errors in Logcat—these usually point to misconfigured google-services.json.
  • Ensure your device has an active internet connection when the app starts up.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:41:43