android - 如何在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);
}
}
解决方案
为你的声音创建一个 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();
}
然后清除您创建的通知。
推荐阅读
- c# - 在 WCF 中使用 REST GET 作为第二个端点
- c++ - add_lvalue_reference/add_rvalue_reference 和 cv 限定类型
- javascript - 如何用正则表达式替换捕获组中的多个值
- react-native - 如何将 src 文件夹添加到 React-native 并绝对导入?
- react-native - 推送通知首选项
- scala - Spark - 写入镶木地板永远不会完成
- json - 表单识别器的请求正文
- typescript - 无法使用 Puppeteer 单击 href
- bash - 如何在 bash 中传输 httpie 请求的标头信息?
- gradle - 如何使用一个名称引用多个任务的输出?