【问题标题】:Android notification - setSound does not workAndroid 通知 - setSound 不起作用
【发布时间】:2014-09-01 22:40:05
【问题描述】:

我已经查看了有关此主题的几个问题,并且似乎都建议在通知生成器中简单地使用.setSound(alarmSound) 会导致手机在通知中播放声音。但是,我正在这样做,但它不起作用。

我可能遗漏了一些东西,但我找不到它是什么。

这是我用来发出通知的代码:

private void newArrivalNotification(String locId, String userId) {

    ...

    mNotificationManager = (NotificationManager)
            this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent mainActivity = new Intent(this, MainActivity.class);

    PendingIntent contentIntent = PendingIntent.getActivity(this, locId.hashCode(),
            mainActivity, 0);

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

    if(alarmSound == null) {
        Log.w("GcmIntentService", "alarmSound is null");
    }

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(title)
                .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(msg))
                .setSound(alarmSound, AudioManager.STREAM_NOTIFICATION)
                .setTicker(msg)
                .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);

    Notification arrivalNotification = mBuilder.build();
    arrivalNotification.defaults |= Notification.DEFAULT_VIBRATE;

    mNotificationManager.notify(NOTIFICATION_ID, arrivalNotification);
}

你能发现我做错了什么吗?我找了几个小时也没找到。

【问题讨论】:

    标签: android audio notifications


    【解决方案1】:

    问题在于您正在使用这行代码修改默认通知行为(声音和振动)。

    Notification arrivalNotification = mBuilder.build();
    arrivalNotification.defaults |= Notification.DEFAULT_VIBRATE;
    mNotificationManager.notify(NOTIFICATION_ID, arrivalNotification);
    

    您可以通过以下方式再次激活它:

    int defaults = 0;
    defaults |= Notification.DEFAULT_SOUND;
    defaults |= Notification.DEFAULT_VIBRATE;
    mBuilder.setDefaults(defaults);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    

    希望对您有所帮助! ;)

    【讨论】:

    • 添加到这个,为了产生振动,而不是使用arrivalNotification.defaults |= Notification.DEFAULT_VIBRATE;,你也可以使用你自己的模式。像long pattern[]={0,2000,500,2000};。你可以使用.setVibrate(pattern)设置振动。它应该工作正常。
    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多