如何在android studio中添加通知声音

时间:2018-06-16 09:19:38

标签: android android-studio notifications

在我的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);

}

}

1 个答案:

答案 0 :(得分:0)

为您的声音创建一个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();

}

然后清除您创建的通知。