firebase / flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
https://firebase.google.com/docs/flutter/setup
BSD 3-Clause "New" or "Revised" License
8.62k stars 3.95k forks source link

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

Closed kroikie closed 3 years ago

kroikie commented 4 years ago

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 commented 4 years ago

@shadowsheep1

The issue at https://github.com/flutter/flutter/issues/26005 has been closed and moved here. Future collaboration on this issue will be done here.

iapicca commented 4 years ago

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

shadowsheep1 commented 4 years ago

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 commented 4 years ago

any solution for that?

iapicca commented 4 years ago

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

behlsoft commented 4 years ago

"[✓] 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 commented 4 years ago

"[✓] 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?

leovu commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="noti_push_app_1"/>

behlsoft commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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.

aldwnesx commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

@behlsoft @iLeafSolutionsPvtLtd @leovu

aldwnesx commented 4 years ago

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"]);

MichaelWestergaard commented 4 years ago

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 commented 4 years ago

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

wisnuwijo commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 4 years ago

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 commented 3 years ago

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

OR

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

evripidesk commented 3 years ago

hello any news with this issue?

harinderratton commented 3 years ago

If you want to use custom sound..you should use onesignal with firebase....its best solution i came with

On Thu, 5 Nov 2020, 12:29 pm evripidesk, notifications@github.com wrote:

hello any news with this issue?

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/FirebaseExtended/flutterfire/issues/523#issuecomment-722184095, or unsubscribe https://github.com/notifications/unsubscribe-auth/AMMTO6IOP5ZOJVMDXDBKEK3SOJEMBANCNFSM4JAIC6FQ .

harinderratton commented 3 years ago

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

harinderratton commented 3 years ago

i have setup custom sound for android and ios app

Salakar commented 3 years ago

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 🤓

shadowsheep1 commented 3 years ago

It has been a long time! 🚀🎉😉

evripidesk commented 3 years ago

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