Skip to content

FCM: Custom notification sound does not play on Android 8.0 device, but plays on Android 6.0 and iOS devices. #6621

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
safield opened this issue Jul 15, 2021 · 1 comment
Labels
Needs Attention This issue needs maintainer attention. resolution: duplicate This issue or pull request already exists type: bug Something isn't working

Comments

@safield
Copy link

safield commented Jul 15, 2021

I am trying to configure my flutter app to play a custom notification sound when an FCM notification arrives. The custom sound currently plays correctly on iOS devices and Android 6.0 devices, but does not work on my Android 8.0 device. I have specified a notification channel and still the notification sound does not play.

I have written a minimal example project that is as follows...

main.dart

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    asyncInit();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FCM Test"),
      ),
      body: Container(),
    );
  }

  void asyncInit() async {
    await Firebase.initializeApp();
    var messaging = FirebaseMessaging.instance;
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
    } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
      print('User granted provisional permission');
    } else {
      print('User declined or has not accepted permission');
    }
    await messaging.subscribeToTopic('all');
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');
      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });
  }
}

MainActivity.kt

class MainActivity: FlutterActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val mChannel = NotificationChannel("test_channel_id", "Test Notification Channel", NotificationManager.IMPORTANCE_HIGH)
            mChannel.description = "Channel to test alerts"
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(mChannel)
        }
    }

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myapp.notificationTestApp">
   <application
        android:label="notification_test_app"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>

            <meta-data
                android:name="com.google.firebase.messaging.default_notification_channel_id"
                android:value="test_channel_id" />
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

pubspec.yaml

name: notification_test_app
description: A new Flutter project.

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  firebase_core: ^1.3.0
  firebase_messaging: ^10.0.2

  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

node.js app.js backend

const { messaging } = require('firebase-admin');
var admin = require('firebase-admin');

console.log(process.cwd());

var serviceAccount = require("path to your service key");

const topic = 'all';

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

const message = {
    notification: {
        title: "Test Notification",
        body: "This is just a test",
    },
    topic: topic,
    android: {
        notification: {
            sound: 'alert.wav',
            channel_id: 'test_channel_id'
        }
    }
};


admin.messaging().send(message).then(response => {
    console.log("Successfully sent message:", response);
})
.catch(function (error) {
    console.error("Error sending message:", error);
});
@safield safield added Needs Attention This issue needs maintainer attention. type: bug Something isn't working labels Jul 15, 2021
@markusaksli-nc markusaksli-nc added the triage Issue is currently being triaged. label Jul 16, 2021
@markusaksli-nc
Copy link
Contributor

Hi @safield
There is already an open issue to track this #4521
Could you please comment the android version information on the mentioned issue?
Closing this as a duplicate.
Thank you

@markusaksli-nc markusaksli-nc added resolution: duplicate This issue or pull request already exists and removed triage Issue is currently being triaged. labels Jul 16, 2021
@firebase firebase locked and limited conversation to collaborators Aug 16, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Needs Attention This issue needs maintainer attention. resolution: duplicate This issue or pull request already exists type: bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants