Skip to content
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

[firebase_messaging] FCM custom sound on Android API level >= 26 it seems it doesn't work #523

Closed
kroikie opened this issue Oct 13, 2019 · 34 comments
Labels
impact: crowd Affects many people, though not necessarily a specific customer with an assigned label. (P2) platform: android Issues / PRs which are specifically for Android. plugin: messaging type: bug Something isn't working type: documentation Improvements or additions to documentation

Comments

@kroikie
Copy link
Collaborator

kroikie commented Oct 13, 2019

Answering this SO question it came out that on devices running Android API level >= 26 push notification custom sounds it doesn't work, but the default sound it's played. All works fine on devices running Android API level < 26.

This the notification payload used during testing:

{
 "to" : "my_device_token",
 "collapse_key" : "type_a",
 "priority" : "high",
 "notification" : {
     "body" : "Test Notification body for custom sound {{datestamp}}",
     "title": "Custom sound alert.mp3",
     "sound": "alert.mp3"
 }
}

This my flutter doctor -v

$ flutter doctor -v

[✓] Flutter (Channel beta, v1.0.0, on Mac OS X 10.14.1 18B75, locale en-IT)
    • Flutter version 1.0.0 at /Users/shadowsheep/flutter/flutter
    • Framework revision 5391447fae (5 weeks ago), 2018-11-29 19:41:26 -0800
    • Engine revision 7375a0f414
    • Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

[✓] Android toolchain - develop for Android devices (Android SDK 28.0.3)
    • Android SDK at /Users/shadowsheep/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.1, Build version 10B61
    • ios-deploy 1.9.4
    • CocoaPods version 1.5.3

[✓] Android Studio (version 3.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 31.3.3
    • Dart plugin version 182.5124
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] VS Code (version 1.30.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 2.21.1

[✓] Connected device (2 available)
    [...]

• No issues found!

Had we missed something?

@kroikie
Copy link
Collaborator Author

kroikie commented Oct 13, 2019

@shadowsheep1

The issue at flutter/flutter#26005 has been closed and moved here. Future collaboration on this issue will be done here.

@iapicca
Copy link

iapicca commented Oct 22, 2019

Hi @shadowsheep1
Did the proposed solution worked for you?
If are you still experiencing this issue
with the latest version of Flutter and FlutterFire plugin
can you please provide your updated flutter doctor -v
and your and your flutter run --verbose/flutter build --verbose ?
Also, to better address the issue, would be helpful
if you could post a self contained app on github
or the steps to reproduce it.
Thank you

@iapicca iapicca added the blocked: customer-response Waiting for customer response, e.g. more information was requested. label Oct 22, 2019
@shadowsheep1
Copy link

Hi @iapicca . I didn’t try the workaround ‘cause, well, it’s a workaround. And I did’t try with the latest version ‘cause the need for the custom sound wasn’t mine but it’s of the SO question’s OP. So if you tell me that this issue has been solved I believe you [-;

@lyseiha
Copy link

lyseiha commented Nov 3, 2019

any solution for that?

@iapicca
Copy link

iapicca commented Nov 20, 2019

Hi @lyseiha
could you please provide your flutter doctor -v
and your flutter run --verbose (when receiving the notification)?
Also, to better address the issue, would be helpful
if you could post a minimal code sample to reproduce the problem
Thank you

@iapicca iapicca added type: bug Something isn't working blocked: customer-response Waiting for customer response, e.g. more information was requested. and removed blocked: customer-response Waiting for customer response, e.g. more information was requested. labels Nov 20, 2019
@behlsoft
Copy link

behlsoft commented Dec 3, 2019

"[✓] Flutter (Channel stable, v1.9.1+hotfix.6, on Mac OS X 10.14.6 18G95, locale en-IN)
• Flutter version 1.9.1+hotfix.6 at /Users/rakeshkumar/Downloads/flutter
• Framework revision 68587a0916 (3 months ago), 2019-09-13 19:46:58 -0700
• Engine revision b863200c37
• Dart version 2.5.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
• Android SDK at /Users/rakeshkumar/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.2
• Java binary at: /Library/Java/JavaVirtualMachines/jdk-13.0.1.jdk/Contents/Home/bin/java
• Java version Java(TM) SE Runtime Environment (build 13.0.1+9)
✗ Android license status unknown.
Try re-installing or updating your Android SDK Manager.
See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.

[✓] Xcode - develop for iOS and macOS (Xcode 11.2.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.2.1, Build version 11B500
• CocoaPods version 1.8.4

[!] Android Studio (not installed)
• Android Studio not found; download from https://developer.android.com/studio/index.html
(or visit https://flutter.dev/setup/#android-setup for detailed instructions).

[✓] Connected device (2 available)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 10 (API 29) (emulator)
• iPhone 11 Pro Max • B549CC74-D155-49AC-AF86-DC4FF45930E0 • ios • com.apple.CoreSimulator.SimRuntime.iOS-13-2 (simulator)

! Doctor found issues in 2 categories."

I don't know why it shows Android Studio is not installed, I am working on Android Studio only

{notification: {title: Earthquake, body: Earthquake hit north India}, data: {id: 909090, desc: An earthquake hit northern region of India measuring 9 at the Richter scale which can result to landslide in higher regions of Himachal Pardesh or Uttarakhand You may please confirm about your safety., category: Earthquake, sound: alarm.mp3, title: Earthquake hit north India, click_action: FLUTTER_NOTIFICATION_CLICK}}

@behlsoft
Copy link

behlsoft commented Dec 3, 2019

"[✓] Flutter (Channel stable, v1.9.1+hotfix.6, on Mac OS X 10.14.6 18G95, locale en-IN)
• Flutter version 1.9.1+hotfix.6 at /Users/rakeshkumar/Downloads/flutter
• Framework revision 68587a0916 (3 months ago), 2019-09-13 19:46:58 -0700
• Engine revision b863200c37
• Dart version 2.5.0

[!] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
• Android SDK at /Users/rakeshkumar/Library/Android/sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.2
• Java binary at: /Library/Java/JavaVirtualMachines/jdk-13.0.1.jdk/Contents/Home/bin/java
• Java version Java(TM) SE Runtime Environment (build 13.0.1+9)
✗ Android license status unknown.
Try re-installing or updating your Android SDK Manager.
See https://developer.android.com/studio/#downloads or visit https://flutter.dev/setup/#android-setup for detailed instructions.

[✓] Xcode - develop for iOS and macOS (Xcode 11.2.1)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Xcode 11.2.1, Build version 11B500
• CocoaPods version 1.8.4

[!] Android Studio (not installed)
• Android Studio not found; download from https://developer.android.com/studio/index.html
(or visit https://flutter.dev/setup/#android-setup for detailed instructions).

[✓] Connected device (2 available)
• Android SDK built for x86 • emulator-5554 • android-x86 • Android 10 (API 29) (emulator)
• iPhone 11 Pro Max • B549CC74-D155-49AC-AF86-DC4FF45930E0 • ios • com.apple.CoreSimulator.SimRuntime.iOS-13-2 (simulator)

! Doctor found issues in 2 categories."

I don't know why it shows Android Studio is not installed, I am working on Android Studio only

{notification: {title: Earthquake, body: Earthquake hit north India}, data: {id: 909090, desc: An earthquake hit northern region of India measuring 9 at the Richter scale which can result to landslide in higher regions of Himachal Pardesh or Uttarakhand You may please confirm about your safety., category: Earthquake, sound: alarm.mp3, title: Earthquake hit north India, click_action: FLUTTER_NOTIFICATION_CLICK}}

and if you say sound should come in 'notification' the how I can do that with FCM console?

@iapicca iapicca removed the blocked: customer-response Waiting for customer response, e.g. more information was requested. label Dec 13, 2019
@leovu
Copy link

leovu commented Jan 2, 2020

I added these code in MainActivity.kt in onCreate()

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

          val soundUri: Uri = Uri.parse(
                  "android.resource://" +
                          applicationContext.packageName +
                          "/" +
                          com.workerteam.ksoft.workerapp.R.raw.alert_tone)

          val audioAttributes = AudioAttributes.Builder()
                  .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                  .setUsage(AudioAttributes.USAGE_ALARM)
                  .build()

          val channel = NotificationChannel("noti_push_app_1",
                  "noti_push_app",
                  NotificationManager.IMPORTANCE_HIGH)
          channel.setSound(soundUri, audioAttributes)

          (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
                  .createNotificationChannel(channel)
      }

and the payload I used :

"notification": {
"title": "dsadasdascsxcxc",
"body": "Tao nè vừa yêu cầu công việc của bạn",
"content_available": true,
"sound": "alert_tone.mp3",
"android_channel_id": "noti_push_app_1"
},

I already got the custom sound for android api level > 26 . Put this here if someone needs.

@iLeafSolutionsPvtLtd
Copy link

iLeafSolutionsPvtLtd commented Jan 7, 2020

import android.app.NotificationChannel
import android.app.NotificationManager
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  val soundUri: Uri = Uri.parse(
          "android.resource://" +
                  applicationContext.packageName +
                  "/" +
                  R.raw.sharp)

  val audioAttributes = AudioAttributes.Builder()
          .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
          .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
          .build()

  val channel = NotificationChannel("noti_push_app_1",
          "noti_push_app",
          NotificationManager.IMPORTANCE_HIGH)
  channel.setSound(soundUri, audioAttributes)

  val notificationManager = getSystemService(NotificationManager::class.java)
  notificationManager.createNotificationChannel(channel)

}
GeneratedPluginRegistrant.registerWith(this)

}

}

  1. Add notification sound file in res > raw folder. Add the folder if it's not there
  2. Open your project as Android
  3. Add above code in onCreate
  4. Run the project and check whether notification channel has created by checking the app info
  5. Specify the channel_id in manifest as follows

@iLeafSolutionsPvtLtd

This comment has been minimized.

@behlsoft
Copy link

I added these code in MainActivity.kt in onCreate()

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

      val soundUri: Uri = Uri.parse(
              "android.resource://" +
                      applicationContext.packageName +
                      "/" +
                      com.workerteam.ksoft.workerapp.R.raw.alert_tone)

      val audioAttributes = AudioAttributes.Builder()
              .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
              .setUsage(AudioAttributes.USAGE_ALARM)
              .build()

      val channel = NotificationChannel("noti_push_app_1",
              "noti_push_app",
              NotificationManager.IMPORTANCE_HIGH)
      channel.setSound(soundUri, audioAttributes)

      (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
              .createNotificationChannel(channel)
  }

and the payload I used :

"notification": {
"title": "dsadasdascsxcxc",
"body": "Tao nè vừa yêu cầu công việc của bạn",
"content_available": true,
"sound": "alert_tone.mp3",
"android_channel_id": "noti_push_app_1"
},

I already got the custom sound for android api level > 26 . Put this here if someone needs.

Its working guys thanks!

@thesmalleyes
Copy link

import android.app.NotificationChannel
import android.app.NotificationManager
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  val soundUri: Uri = Uri.parse(
          "android.resource://" +
                  applicationContext.packageName +
                  "/" +
                  R.raw.sharp)

  val audioAttributes = AudioAttributes.Builder()
          .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
          .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
          .build()

  val channel = NotificationChannel("noti_push_app_1",
          "noti_push_app",
          NotificationManager.IMPORTANCE_HIGH)
  channel.setSound(soundUri, audioAttributes)

  val notificationManager = getSystemService(NotificationManager::class.java)
  notificationManager.createNotificationChannel(channel)

}
GeneratedPluginRegistrant.registerWith(this)

}

}

  1. Add notification sound file in res > raw folder. Add the folder if it's not there
  2. Open your project as Android
  3. Add above code in onCreate
  4. Run the project and check whether notification channel has created by checking the app info
  5. Specify the channel_id in manifest as follows

is anybody has a java example like this code?

@racacere
Copy link

import android.app.NotificationChannel
import android.app.NotificationManager
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  val soundUri: Uri = Uri.parse(
          "android.resource://" +
                  applicationContext.packageName +
                  "/" +
                  R.raw.sharp)

  val audioAttributes = AudioAttributes.Builder()
          .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
          .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
          .build()

  val channel = NotificationChannel("noti_push_app_1",
          "noti_push_app",
          NotificationManager.IMPORTANCE_HIGH)
  channel.setSound(soundUri, audioAttributes)

  val notificationManager = getSystemService(NotificationManager::class.java)
  notificationManager.createNotificationChannel(channel)

}
GeneratedPluginRegistrant.registerWith(this)

}
}

  1. Add notification sound file in res > raw folder. Add the folder if it's not there
  2. Open your project as Android
  3. Add above code in onCreate
  4. Run the project and check whether notification channel has created by checking the app info
  5. Specify the channel_id in manifest as follows

is anybody has a java example like this code?

A java version of this:

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;

public class MainActivity extends FlutterActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      Uri soundUri = Uri.parse( "android.resource://" +  getApplicationContext().getPackageName() + "/" +  R.raw.[SOUND_NAME]);

      AudioAttributes audioAttributes = new AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .setUsage(AudioAttributes.USAGE_ALARM)
        .build();

      // Creating Channel
      NotificationChannel channel = new NotificationChannel("[CHANNEL_ID]", "[CHANNEL NAME]", NotificationManager.IMPORTANCE_HIGH);
      channel.setSound(soundUri, audioAttributes);

      NotificationManager notificationManager = getSystemService(NotificationManager.class);
      notificationManager.createNotificationChannel(channel);
    }
    GeneratedPluginRegistrant.registerWith(this);
  }
}

@thesmalleyes
Copy link

import android.app.NotificationChannel
import android.app.NotificationManager
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  val soundUri: Uri = Uri.parse(
          "android.resource://" +
                  applicationContext.packageName +
                  "/" +
                  R.raw.sharp)

  val audioAttributes = AudioAttributes.Builder()
          .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
          .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
          .build()

  val channel = NotificationChannel("noti_push_app_1",
          "noti_push_app",
          NotificationManager.IMPORTANCE_HIGH)
  channel.setSound(soundUri, audioAttributes)

  val notificationManager = getSystemService(NotificationManager::class.java)
  notificationManager.createNotificationChannel(channel)

}
GeneratedPluginRegistrant.registerWith(this)

}
}

  1. Add notification sound file in res > raw folder. Add the folder if it's not there
  2. Open your project as Android
  3. Add above code in onCreate
  4. Run the project and check whether notification channel has created by checking the app info
  5. Specify the channel_id in manifest as follows

is anybody has a java example like this code?

A java version of this:

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;

public class MainActivity extends FlutterActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      Uri soundUri = Uri.parse( "android.resource://" +  getApplicationContext().getPackageName() + "/" +  R.raw.[SOUND_NAME]);

      AudioAttributes audioAttributes = new AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .setUsage(AudioAttributes.USAGE_ALARM)
        .build();

      // Creating Channel
      NotificationChannel channel = new NotificationChannel("[CHANNEL_ID]", "[CHANNEL NAME]", NotificationManager.IMPORTANCE_HIGH);
      channel.setSound(soundUri, audioAttributes);

      NotificationManager notificationManager = getSystemService(NotificationManager.class);
      notificationManager.createNotificationChannel(channel);
    }
    GeneratedPluginRegistrant.registerWith(this);
  }
}

thanks, it's work

@sendtomitesh
Copy link

import android.app.NotificationChannel
import android.app.NotificationManager
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  val soundUri: Uri = Uri.parse(
          "android.resource://" +
                  applicationContext.packageName +
                  "/" +
                  R.raw.sharp)

  val audioAttributes = AudioAttributes.Builder()
          .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
          .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
          .build()

  val channel = NotificationChannel("noti_push_app_1",
          "noti_push_app",
          NotificationManager.IMPORTANCE_HIGH)
  channel.setSound(soundUri, audioAttributes)

  val notificationManager = getSystemService(NotificationManager::class.java)
  notificationManager.createNotificationChannel(channel)

}
GeneratedPluginRegistrant.registerWith(this)

}
}

  1. Add notification sound file in res > raw folder. Add the folder if it's not there
  2. Open your project as Android
  3. Add above code in onCreate
  4. Run the project and check whether notification channel has created by checking the app info
  5. Specify the channel_id in manifest as follows

is anybody has a java example like this code?

A java version of this:

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;

public class MainActivity extends FlutterActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      Uri soundUri = Uri.parse( "android.resource://" +  getApplicationContext().getPackageName() + "/" +  R.raw.[SOUND_NAME]);

      AudioAttributes audioAttributes = new AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .setUsage(AudioAttributes.USAGE_ALARM)
        .build();

      // Creating Channel
      NotificationChannel channel = new NotificationChannel("[CHANNEL_ID]", "[CHANNEL NAME]", NotificationManager.IMPORTANCE_HIGH);
      channel.setSound(soundUri, audioAttributes);

      NotificationManager notificationManager = getSystemService(NotificationManager.class);
      notificationManager.createNotificationChannel(channel);
    }
    GeneratedPluginRegistrant.registerWith(this);
  }
}

thanks, it's work

It worked well!. Thanks.

@iapicca iapicca added the impact: crowd Affects many people, though not necessarily a specific customer with an assigned label. (P2) label Feb 12, 2020
@aldwnesx
Copy link

Where is MainActivity.kt?

I only found one with thiis content:

`package com.example.app_notify

import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugins.GeneratedPluginRegistrant

class MainActivity: FlutterActivity() {
override fun configureFlutterEngine(@nonnull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
}
}

`

is this right?

@aldwnesx
Copy link

I tried your examples but get

Expecting a top level declaration
Unresolved reference: sharp
Type mismatch: inferred type is MainActivity but FlutterEngine was expected

@aldwnesx
Copy link

@aldwnesx
Copy link

aldwnesx commented Mar 25, 2020

import android.app.NotificationChannel
import android.app.NotificationManager
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  val soundUri: Uri = Uri.parse(
          "android.resource://" +
                  applicationContext.packageName +
                  "/" +
                  R.raw.sharp)

  val audioAttributes = AudioAttributes.Builder()
          .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
          .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
          .build()

  val channel = NotificationChannel("noti_push_app_1",
          "noti_push_app",
          NotificationManager.IMPORTANCE_HIGH)
  channel.setSound(soundUri, audioAttributes)

  val notificationManager = getSystemService(NotificationManager::class.java)
  notificationManager.createNotificationChannel(channel)

}
GeneratedPluginRegistrant.registerWith(this)

}
}

  1. Add notification sound file in res > raw folder. Add the folder if it's not there
  2. Open your project as Android
  3. Add above code in onCreate
  4. Run the project and check whether notification channel has created by checking the app info
  5. Specify the channel_id in manifest as follows

is anybody has a java example like this code?

A java version of this:

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;

public class MainActivity extends FlutterActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      Uri soundUri = Uri.parse( "android.resource://" +  getApplicationContext().getPackageName() + "/" +  R.raw.[SOUND_NAME]);

      AudioAttributes audioAttributes = new AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .setUsage(AudioAttributes.USAGE_ALARM)
        .build();

      // Creating Channel
      NotificationChannel channel = new NotificationChannel("[CHANNEL_ID]", "[CHANNEL NAME]", NotificationManager.IMPORTANCE_HIGH);
      channel.setSound(soundUri, audioAttributes);

      NotificationManager notificationManager = getSystemService(NotificationManager.class);
      notificationManager.createNotificationChannel(channel);
    }
    GeneratedPluginRegistrant.registerWith(this);
  }
}

thanks, it's work

It worked well!. Thanks.

error: expected
Uri soundUri = Uri.parse( "android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.["audio.mp3"]);

@Ehesp Ehesp added type: documentation Improvements or additions to documentation platform: android Issues / PRs which are specifically for Android. labels Apr 21, 2020
@MichaelWestergaard
Copy link

MichaelWestergaard commented Jun 4, 2020

I get the problem when building an apk and installing it on the phone. I have no problems at all with custom sounds when running the app with flutter run. I did check the apk file, and all the audio files are still in the res/raw folder. It is only the default sound that works, anything else makes no sound. Anyone knows a fix for that?

UPDATE:
Building with --no-shrink solved my problem.

@aliakkawi
Copy link

In my case event the default sound is not working on Android devices, on iOS it is working good.

@wisnuwijo
Copy link

wisnuwijo commented Aug 3, 2020

import android.app.NotificationChannel
import android.app.NotificationManager
import android.media.AudioAttributes
import android.net.Uri
import android.os.Build
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

  val soundUri: Uri = Uri.parse(
          "android.resource://" +
                  applicationContext.packageName +
                  "/" +
                  R.raw.sharp)

  val audioAttributes = AudioAttributes.Builder()
          .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
          .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
          .build()

  val channel = NotificationChannel("noti_push_app_1",
          "noti_push_app",
          NotificationManager.IMPORTANCE_HIGH)
  channel.setSound(soundUri, audioAttributes)

  val notificationManager = getSystemService(NotificationManager::class.java)
  notificationManager.createNotificationChannel(channel)

}
GeneratedPluginRegistrant.registerWith(this)

}
}

  1. Add notification sound file in res > raw folder. Add the folder if it's not there
  2. Open your project as Android
  3. Add above code in onCreate
  4. Run the project and check whether notification channel has created by checking the app info
  5. Specify the channel_id in manifest as follows

is anybody has a java example like this code?

A java version of this:

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;

public class MainActivity extends FlutterActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      Uri soundUri = Uri.parse( "android.resource://" +  getApplicationContext().getPackageName() + "/" +  R.raw.[SOUND_NAME]);

      AudioAttributes audioAttributes = new AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
        .setUsage(AudioAttributes.USAGE_ALARM)
        .build();

      // Creating Channel
      NotificationChannel channel = new NotificationChannel("[CHANNEL_ID]", "[CHANNEL NAME]", NotificationManager.IMPORTANCE_HIGH);
      channel.setSound(soundUri, audioAttributes);

      NotificationManager notificationManager = getSystemService(NotificationManager.class);
      notificationManager.createNotificationChannel(channel);
    }
    GeneratedPluginRegistrant.registerWith(this);
  }
}

Does it right if I write like this one below?

  Uri soundUri = Uri.parse( "android.resource://" +  getApplicationContext().getPackageName() + "/" +  R.raw.tone);

here is my full MainActivity.java code.
NOTE : My sound name is tone.mp3

package com.firecek.firecek;

import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;

public class MainActivity extends FlutterActivity {
@OverRide
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  Uri soundUri = Uri.parse( "android.resource://" +  getApplicationContext().getPackageName() + "/" +  R.raw.tone);

  AudioAttributes audioAttributes = new AudioAttributes.Builder()
    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
    .setUsage(AudioAttributes.USAGE_ALARM)
    .build();

  // Creating Channel
  NotificationChannel channel = new NotificationChannel("Channel-Id", "Channel-Name", NotificationManager.IMPORTANCE_HIGH);
  channel.setSound(soundUri, audioAttributes);

  NotificationManager notificationManager = getSystemService(NotificationManager.class);
  notificationManager.createNotificationChannel(channel);
}

GeneratedPluginRegistrant.registerWith(this);

}
}

It still doesn't work at my case

@sc00n
Copy link

sc00n commented Aug 13, 2020

After the flutter embedding v2
<meta-data android:name="flutterEmbedding" android:value="2" /> </manifest>
the above solutions didn't work for me anymore (for example, you get Type mismatch: inferred type is MainActivity but FlutterEngine was expected).

Here is the code (the full MainActivity.java) that I used that worked for me:


import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
import androidx.annotation.NonNull;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
//import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;


public class MainActivity extends FlutterActivity {

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Uri soundUri = Uri.parse( "android.resource://" +  getApplicationContext().getPackageName() + "/" +  R.raw.test1);

            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build();

            // Creating Channel
            NotificationChannel channel = new NotificationChannel("noti_push_app_1",
                    "noti_push_app", NotificationManager.IMPORTANCE_HIGH);
            channel.setSound(soundUri, audioAttributes);

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);

        }
    }

}

With the following in the notification:

"sound": "test1.mp3",
"android_channel_id": "noti_push_app_1"

and the file test1.mp3 in the res/raw folder

@krish-bhanushali
Copy link

After the flutter embedding v2
<meta-data android:name="flutterEmbedding" android:value="2" /> </manifest>
the above solutions didn't work for me anymore (for example, you get Type mismatch: inferred type is MainActivity but FlutterEngine was expected).

Here is the code (the full MainActivity.java) that I used that worked for me:


import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;
import androidx.annotation.NonNull;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
//import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;


public class MainActivity extends FlutterActivity {

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);



        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Uri soundUri = Uri.parse( "android.resource://" +  getApplicationContext().getPackageName() + "/" +  R.raw.test1);

            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build();

            // Creating Channel
            NotificationChannel channel = new NotificationChannel("noti_push_app_1",
                    "noti_push_app", NotificationManager.IMPORTANCE_HIGH);
            channel.setSound(soundUri, audioAttributes);

            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);

        }
    }

}

With the following in the notification:

"sound": "test1.mp3",
"android_channel_id": "noti_push_app_1"

and the file test1.mp3 in the res/raw folder

This really helped a lot

@Gogeta999
Copy link

I added these code in MainActivity.kt in onCreate()

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

          val soundUri: Uri = Uri.parse(
                  "android.resource://" +
                          applicationContext.packageName +
                          "/" +
                          com.workerteam.ksoft.workerapp.R.raw.alert_tone)

          val audioAttributes = AudioAttributes.Builder()
                  .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                  .setUsage(AudioAttributes.USAGE_ALARM)
                  .build()

          val channel = NotificationChannel("noti_push_app_1",
                  "noti_push_app",
                  NotificationManager.IMPORTANCE_HIGH)
          channel.setSound(soundUri, audioAttributes)

          (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
                  .createNotificationChannel(channel)
      }

and the payload I used :

"notification": {
"title": "dsadasdascsxcxc",
"body": "Tao nè vừa yêu cầu công việc của bạn",
"content_available": true,
"sound": "alert_tone.mp3",
"android_channel_id": "noti_push_app_1"
},

I already got the custom sound for android api level > 26 . Put this here if someone needs.

Really helped a lot

@harinderratton
Copy link

ISSUE: unable to play custom sound when getting fcm in background of ionic app
Hello everyone,
im creating an app in ionic 4
im sending push notification from node.js fcm-push.

---following is my node code----
var message = {
to : id',

        notification : {
            title : 'Title ',
            body : 'some Body',
            sound : 'police_siren',
            soundname: 'police_siren',
           
        },
        data: {
            param1:"",
            param2:"",
            android_channel_id: 'emergency',
            soundname: 'police_siren',     //also checked with police_siren.mp3
          }
        };

----Following is my ionic code----

var channelId = 'emergency';
  this.push.createChannel({
  id: channelId,
  description: 'Emergency Channel',
  importance: 4,
  sound: 'police_siren',
  }).then(() => console.log('Channel created'));

 const options: PushOptions = {
   android: {  },
    ios: {
        alert: 'true',
        badge: true,
        sound: 'true'
    },
    windows: {},
    browser: {
        pushServiceURL: 'http://push.api.phonegap.com/v1/push'
    }
 }

const pushObject: PushObject = this.push.init(options);

  pushObject.on('notification').subscribe((notification: any) => {
      console.log('message', notification.message);
      let self = this;
      if (notification.additionalData.foreground) {

      } else {

      }
  });

----Following is XML File code----

And i have place police_siren.mp3 file in assets/sound/ and also in res/raw directory.

Please somebody help me figure out what im skipping in this,

@riskiadi
Copy link

can I ask, is sound using .mp3 or not?
"notification": {
"sound": "doorbell_sound.mp3"
},

OR

"notification": {
"sound": "doorbell_sound"
},

@evripidesk
Copy link

hello any news with this issue?

@harinderratton
Copy link

harinderratton commented Nov 5, 2020 via email

@harinderratton
Copy link

harinderorg@gmail.com is my email, you can contact me there or on whatsapp +919417375191 for any help

@harinderratton
Copy link

i have setup custom sound for android and ios app

@Salakar
Copy link
Member

Salakar commented Nov 5, 2020

Hey all 👋

As part of our roadmap (#2582) we've just shipped a complete rework of the firebase_messaging plugin that aims to solve this and many other issues.

If you can, please try out the dev release (see the migration guide for upgrading and for changes) and if you have any feedback then join in the discussion here.

Given the scope of the rework I'm going to go ahead and close this issue in favor of trying out the latest plugin.

Thanks everyone 🤓

@Salakar Salakar closed this as completed Nov 5, 2020
@shadowsheep1
Copy link

It has been a long time! 🚀🎉😉

@evripidesk
Copy link

I tried the firebase_messaging 8.0.0 dev 8 and the custom sound on android still not working

@firebase firebase locked and limited conversation to collaborators Dec 6, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
impact: crowd Affects many people, though not necessarily a specific customer with an assigned label. (P2) platform: android Issues / PRs which are specifically for Android. plugin: messaging type: bug Something isn't working type: documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests