簡體   English   中英

Android通知自定義聲音不播放

[英]Android notification custom sound not playing

我希望在彈出通知時播放自定義mp3聲音。 這是我的代碼:

public class firebase_connection extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(@NonNull RemoteMessage message) {
        String title = Objects.requireNonNull(message.getNotification()).getTitle();
        String body = message.getNotification().getBody();
        Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + getPackageName() + "/raw/music.mp3");
        super.onMessageReceived(message);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("MyNotifications","MyNotifications", NotificationManager.IMPORTANCE_DEFAULT);
            AudioAttributes aud_att = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                    .build();
            channel.setSound(sound,aud_att);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);

            Notification.Builder notification = new Notification.Builder(this,"MyNotifications")
                    .setContentTitle(title)
                    .setContentText(body)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setAutoCancel(true);

            NotificationManagerCompat.from(this).notify(1,notification.build());
        }
    }
}

mp3文件位於res->raw->music.mp3中。 執行代碼后,通知會以默認聲音顯示。 為什么? 我哪里錯了? 請幫我。

我也在我的 logcat 中收到此消息:

W/FirebaseMessaging:AndroidManifest 中缺少默認通知通道元數據。 將使用默認值。

嘗試一次此解決方案

   val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        
        Notification.Builder notification = new Notification.Builder(this,"MyNotifications")
                            .setContentTitle(title)
                            .setContentText(body)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            **.setSound(defaultSoundUri)// Try your Sound here** 
                            .setAutoCancel(true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM