通知振动,屏幕锁定时的声音

Notification vibration, sound when screen is locked

问题

我收到 GCM 通知,但是当我的屏幕被锁定或关闭时,我的振动和声音就不起作用了。 我尝试添加唤醒锁,但从 GCMListenerService 的外观来看,在触发通知时已经有唤醒意图。 我应该怎么做才能让它发挥作用?我丢失的部分在哪里?

编辑

Bundle var2 = var1.getExtras(); var2.remove("message_type"); var2.remove("android.support.content.wakelockid");

代码

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

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notification_icon)
            .setContentTitle(getString(R.string.new_notification))
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setVibrate(new long[] {1000, 1000, 1000})
            .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = notificationBuilder.build();
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_SOUND;

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
    wl.acquire(10000);

    notificationManager.notify(0, notification);

您需要在服务器端代码中添加此标志 delay_while_idle=true。 见 here

编辑

Google 现在对通知有效负载及其处理方式提供合理的解释 -> Notification payloads.

===================

所以事实证明,当您的通知包含 data payloadnotification payload 时,在锁定模式下 Android 正在从播放负载创建通知,即使您已经编写了自定义代码.

不需要唤醒锁 - GcmListenerService 将自行决定是否需要,只要您有 <uses-permission android:name="android.permission.WAKE_LOCK" />

我正在使用 FCM,经过大量的努力(我猜是缺乏文档),我通过从发送到 FCM 的字段中删除通知解决了这个问题,并且只使用了 data。这是我的代码 php:

$fields = array(
    'to' => 'topics/all',
    'data' => array(
        'priority' => 'high',
        'title' => $title,
        'body' => $body,
        'type' => $type));

此外,您还必须将优先级设置为 high,以使其在设备锁定时响铃和振动。

确保您已在清单文件中声明默认通知渠道。

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" 
           android:value="YOUR_CHANNEL_ID"/>