首页 > 解决方案 > 如何在android studio中添加通知声音

问题描述

在我的 android 应用程序中,我想用声音通知用户而不显示通知。

public class MessagingService extends FirebaseMessagingService{
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
 shownotification(remoteMessage.getNotification().getBody());
}
public void shownotification(String message){
    PendingIntent p1=PendingIntent.getActivities(this,0, new Intent[]{new Intent(this, MainActivity.class)}, 0);
    Notification notification=new NotificationCompat.Builder(this)

            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle("Notification")
            .setContentText(message)
            .setContentIntent(p1)
            .setAutoCancel(true)
            .build();
    NotificationManager notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(0,notification);

}

}

标签: androidandroid-studionotifications

解决方案


为你的声音创建一个 Uri

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

并将其添加到您的通知中

.setSound(alarmSound)

并清除您创建的通知。notificationManager.cancelAll();

所以你的代码看起来像这样。

public void shownotification(String message){
 Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
 PendingIntent p1=PendingIntent.getActivities(this,0, new Intent[]{new Intent(this, MainActivity.class)}, 0);
 Notification notification=new NotificationCompat.Builder(this)

        .setSmallIcon(R.drawable.ic_stat_name)
        .setContentTitle("Notification")
        .setContentText(message)
        .setContentIntent(p1)
        .setAutoCancel(true)
        .setSound(alarmSound)
        .build();
 NotificationManager notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
 notificationManager.notify(0,notification);
 notificationManager.cancelAll();

}

然后清除您创建的通知。


推荐阅读