具有自定义声音的Firebase推送通知(Flutter)

时间:2018-11-29 03:22:27

标签: dart flutter

我目前正在使用Firebase消息传递云为我的应用推送通知。我正在尝试为推送通知发出自定义通知声音。我相信可以通过在有效负载中放入“ sound:blabla.mp3”来实现,但是我如何在dart页面中定义声音?

5 个答案:

答案 0 :(得分:2)

使用 flutter_local_notifications

AndroidNotificationDetails androidNotificationsDetails = AndroidNotificationDetails(
       'your other channel id',
       'your other channel name',
       'your other channel description',
        importance: Importance.Max,
        priority: Priority.Max,
        enableLights: true,
        playSound: true,
        sound: RawResourceAndroidNotificationSound('notification'),
);

注意:你应该在android/app/src/main/res/raw/notification.mp3中添加notification.mp3文件,不要忘记指定playSound:

playSound: true,

这在前台/后台和应用程序关闭时对我有用。

答案 1 :(得分:1)

您可以简单地通过调用声音并在firebase configure方法中播放声音来实现此目的。

class Class:
    def action(self, accounts):
        for account in accounts[9:]:
            try:
                self.browser.get(account)
                time.sleep(5)
                like_button = self.browser.find_element_by_xpath(
                                    u'//button[contains(@class, "Heart")]').click()
                self.count_actions()
                print(self.counter_var)
                yield  # Added.
            except selenium.common.exceptions.NoSuchElementException:
                break

    def count_actions(self):
        self.counter_var += 1

    def main(self):
        while True:
            searched_category = random.choice(pool_categories)
            accounts = self.load_category(searched_category)
            for _ in self.action(accounts):  # Iterate through account checks.
                if self.counter_var < self.max_var:  # Too many actions?
                    break

此操作无效,因为如果应用程序在后台运行,则文件不会播放

答案 2 :(得分:1)

要为两个Android都创建自定义通知声音,您需要为您的应用程序预定义通知频道。我使用Flutter Local Notifications插件来做到这一点。您可以在其中为您的Android通知频道指定参数,例如

var androidPlatformChannelSpecifics = AndroidNotificationDetails( 'your other channel id', 'your other channel name', 'your other channel description', sound: RawResourceAndroidNotificationSound('slow_spring_board');

注意:slow_spring_board.mp3存储在应用程序的android\app\src\main\res\raw部分中。调用RawResourceAndroidNotificationSound()

时不要包含文件扩展名

还有其他步骤才能为iOS设备设置它(不支持mp3)。完成所有步骤后,您可以开始处理云消息传递部分,在其中必须参考通知通道ID和声音文件。我建议在该代码中包括音频文件扩展名。

答案 3 :(得分:0)

You must create notification channel first with following code

Application.kt

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.GeneratedPluginRegistrant
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
import io.flutter.plugins.pathprovider.PathProviderPlugin;

import io.flutter.plugin.common.MethodChannel
import android.content.ContextWrapper
import android.content.Intent
import android.content.IntentFilter
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.net.Uri;
import android.media.AudioAttributes;
import android.content.ContentResolver;

class Application : FlutterApplication(), PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
        this.createChannel()
        FlutterFirebaseMessagingService.setPluginRegistrant(this)
    }

    override fun registerWith(registry: PluginRegistry?) {
//        createChannel();
        FirebaseCloudMessagingPluginRegistrant.registerWith(registry);
    }

    private fun createChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Create the NotificationChannel
            val name: String = getString(R.string.default_notification_channel_id)
            val channel = NotificationChannel(name, "default", NotificationManager.IMPORTANCE_HIGH)
            val soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/raw/sample");
            val att = AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                    .build();
            channel.setSound(soundUri, att)

            val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)

            /*
            val id = mapData["id"]
            val name = mapData["name"]
            val descriptionText = mapData["description"]
            val sound = "sample"
            val importance = NotificationManager.IMPORTANCE_HIGH
            val mChannel = NotificationChannel(id, name, importance)
            mChannel.description = descriptionText





            // 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)
            completed = true
             */
        }
    }
}

And android manifest.xml

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.foodlz.orders">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.VIBRATE" />

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name=".Application"
        android:label="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">
            <!-- This keeps the window background of the activity showing
                 until Flutter renders its first frame. It can be removed if
                 there is no splash screen (such as the default splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </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" />

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


        <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_appstore" />

        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorPrimary" />
    </application>


</manifest>


finally you must put your notification sound.wav file in res/raw

that's it

答案 4 :(得分:0)

可以通过flutter_local_notifications插件实现。

首先,您应该为 Android 和 iOS 定义渠道:

const androidPlatformChannel = AndroidNotificationDetails(
  'ANDROID_CHANNEL_ID',
  'Name',
  'Description',
  color: Color.fromARGB(255, 0, 0, 0),
  importance: Importance.max,
  sound: RawResourceAndroidNotificationSound('notification_sound'),
  playSound: true,
  priority: Priority.high,
  showWhen: false,
);

const iOSPlatformChannel = IOSNotificationDetails(
  sound: 'notification_sound.aiff',
  presentAlert: true,
  presentBadge: true,
  presentSound: true,
);

const platformChannel = NotificationDetails(
  android: androidPlatformChannel,
  iOS: iOSPlatformChannel,
);

然后显示通知:

await flutterLocalNotificationsPlugin.show(
      id,
      title,
      body,
      platformChannel,
      payload: notification.payload,
    );

重要提示!notification_sound.aiff 文件应该用 XCode 复制