首页 > 解决方案 > Ionic FCM 通知自定义声音在 android 7 中有效,但在其他系统中无效

问题描述

我正在研究 Ionic FCM 推送通知,在此,我们的要求是在接收通知时添加自定义通知声音。

使用的插件:FCMPush

为此,我们完成了以下代码:

app.component.ts 文件

import { Component } from '@angular/core';
import { NavController, Platform } from '@ionic/angular';
import { FCM } from 'cordova-plugin-fcm-with-dependecy-updated/ionic/ngx';
import { INotificationPayload } from 'cordova-plugin-fcm-with-dependecy-updated';
import { Push } from '@ionic-native/push/ngx';
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent {
  public hasPermission: boolean;
  public token: string;
  public pushPayload: INotificationPayload;

  constructor(private platform: Platform, private fcm: FCM, private nav: NavController,
    private push: Push) {
    this.createChannel();
    this.setupFCM();
  }

  createChannel() {
    // to check if we have permission
    this.push.hasPermission()
      .then((res: any) => {

        if (res.isEnabled) {
          console.log('We have permission to send push notifications');
        } else {
          console.log('We do not have permission to send push notifications');
        }

      });

    // Create a channel (Android O and above). You'll need to provide the id, description and importance properties.
    this.push.createChannel({
      description: 'General Notifications',
      id: 'my_channel_01',
      importance: 5,
      sound: 'shotgun.wav',
      vibration: true,
      visibility: 1,
      badge: false
    }).then(() => console.log('Channel created'));

    // Return a list of currently configured channels
    this.push.listChannels().then((channels) => console.log('List of channels', channels));

  }

  async setupFCM() {
    await this.platform.ready();
    console.log('FCM setup started');

    if (!this.platform.is('cordova')) {
      return;
    }
    console.log('In cordova platform');

    console.log('Subscribing to token updates');
    this.fcm.onTokenRefresh().subscribe((newToken) => {
      this.token = newToken;
      console.log('onTokenRefresh received event with: ', newToken);
    });

    console.log('Subscribing to new notifications');
    this.fcm.onNotification().subscribe((payload) => {
      if (payload.wasTapped) {
        console.log('Received in background');
        this.nav.navigateForward([payload.route], { animated: true });
        console.log(payload.route);
      } else {
        console.log('Received in foreground');
      };
      this.pushPayload = payload;
      console.log('onNotification received event with: ', payload);
    });

    this.hasPermission = await this.fcm.requestPushPermission();
    console.log('requestPushPermission result: ', this.hasPermission);

    this.token = await this.fcm.getToken();
    console.log('getToken result: ', this.token);
    localStorage.setItem('token', this.token);
    this.pushPayload = await this.fcm.getInitialPushPayload();
    console.log('getInitialPushPayload result: ', this.pushPayload);
  }
}

如我们所知,要发送通知,我们可以从 firebase 控制台、手动代码和使用邮递员发送。

方式1邮递员:

标题部分 在此处输入图像描述

身体的一部分 在此处输入图像描述

我在邮递员请求中使用的 URL:https ://fcm.googleapis.com/fcm/send

代码的正文部分或称为 json 对象在这里:

{
    "to": "fPrZ1gnPKdg:APA91bGfUWgbrfZyZdzGy6qMjY2QhR0OVCeRfuwCRXMI0Q0fsT347HWAxIzwbv8EbFrXj8X2HbrwJakATgqFlr9ZQ_1TJMyW-8i6nOMrRf-6QPoPjxz8l_kj61dsydnQDbgh8GwUKLX9",
    "collapse_key": "type_a",
    "notification": {
        "body": "Body of Your Notification",
        "title": "Title of Your Notification",
        "sound": "shotgun.wav",
        "channelId": "my_channel_01",
        "click_action": "FCM_PLUGIN_ACTIVITY"
    },
    "data": {
        "body": "Hello world",
        "title": "Title",
        "sound": "shotgun.wav",
        "route": "/tabs/tab2",
        "channelId": "my_channel_01",
    },
    "priority": "high"
}

方式 2 使用 httpClient 手动请求

postNoti() {
    const body = {
      to: this.token,
      collapse_key: 'type_a',
      notification: {
        body: 'Body of Your Notification',
        title: 'Title of Your Notification',
        sound: 'shotgun.wav',
        channelId: 'testchannel1',
        click_action: 'FCM_PLUGIN_ACTIVITY'
      },
      data: {
        body: 'Hello world',
        title: 'Title',
        sound: 'shotgun.wav',
        route: this.pathName
      },
      priority: 'high'
    };

    const headers = new HttpHeaders({
      Authorization: 'key=AAAA8QvR4ds:APA91bHkTOY65qN8fPE3uk2Y7RkohTJc7VTm9j_JeWHj5xXYAV7ryxZ_p7O6z9dn_-XP9n2PuvD9A406ElsQB2NEKV58QehAv109fuTkcYwCcoyzPokQut4RCzFl5ICWfadeUm6Cmw5s',
      'Content-Type': 'application/json',
    });

    setTimeout(() => {
      this.httpClient
        .post('https://fcm.googleapis.com/fcm/send', body, { headers })
        .subscribe((res) => {
          console.log(res);
        }, (err) => {
          console.log(err);
        });
    }, 10000);
  }

在这段代码中,我添加了一个超时,我使用了一个超时来发送通知,因为当我们的应用程序打开并且收到通知时,它不会显示在通知栏中。因此,在我单击 sendNoti() 函数后,我将关闭应用程序,以便看到收到的通知。

在离子论坛上的这个问题中,我作为参考并使用离子推送插件创建了一个频道,但我仍然没有听到声音。

我尝试了 3 天,但没有解决我的问题。请帮助我或指导我解决这个问题。如果有人需要更多细节评论它,我会分享。先感谢您。

标签: androidfirebaseionic-frameworkpush-notificationfirebase-cloud-messaging

解决方案


推荐阅读