【发布时间】:2018-07-13 16:53:10
【问题描述】:
这是扩展BroadcastReceiver 的myService 类。如果我不调用 showNotif,通知声音只会播放一次。当我这样做时,声音会播放两次。谁能帮助我并告诉我这段代码有什么问题?谢谢。
public class myService extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
showNotif(context, id, name);
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(context, notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
private void showNotif(Context context, Integer id, String name) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, id.toString());
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.alert)
.setTicker("bla")
.setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
.setContentTitle(name)
.setContentText("blabla")
.setContentInfo("blablabla");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(context, newClass.class);
mIntent .putExtra("ID", id);
mIntent .putExtra("NAME", name);
PendingIntent mPending = PendingIntent.getActivity(context, id, mIntent , PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(mPending);
notificationManager.notify(id, notificationBuilder.build());
}
}
【问题讨论】:
-
DEFAULT_ALL 包括 DEFAULT_SOUND,因此除了正在播放的铃声之外,通知还会播放声音:Android disable notification sounds
-
哦,我现在明白了...我刚刚删除了“.setDefaults(Notification.DEFAULT_ALL)”,现在一切正常。谢谢!
-
Np。很高兴它正在工作:):):)
标签: android notifications broadcastreceiver