服务.startForeground震动设备

4

我正在使用startForeground()方法来启动我的一个服务:

NotificationCompat.Builder notifBuilder = 
                              new NotificationCompat.Builder(this, "my_channel")
                              .setContentTitle("Loading");
startForeground(1, notifBuilder.build());

问题在于,由于我正在使用我的独特通道进行通知并且它具有振动功能:
NotificationManager notificationManager =
      (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel = 
        new NotificationChannel("my_channel", "Notifications", NotificationManager.IMPORTANCE_DEFAUL);
mChannel.enableLights(true);
mChannel.enableVibration(true);
notificationManager.createNotificationChannel(mChannel);

startForeground() 调用会触发震动。

尝试了一些配置:

无效:notifBuilder.setVibrate(new long[]{0,0})notifBuilder.setDefaults(~Notification.DEFAULT_VIBRATE)

在我的设备上有效的是 notifBuilder.setVibrate(null) 或使用未注册的通道 ID,但我不确定这是否会导致其他版本或设备崩溃。

如何避免声明新通道而不触发震动?

2个回答

6
您正在创建使用IMPORTANCE_DEFAULTNotificationChannel,根据文档,这表示:

默认通知重要性:在任何地方显示,发出声音,但不会在视觉上干扰。

您可能想使用IMPORTANCE_LOW

低通知重要性:在任何地方显示,但不会干扰。

如果您希望"my_channel"保持IMPORTANCE_DEFAULT,则可以为此服务创建具有不同重要性的新渠道。


1
振动模式是特定于该通知渠道的,因此在发布通知时,您需要在通知渠道上禁用它,然后为您希望振动的通知重新启用它。您还可以针对不同优先级设置单独的通知渠道,如文档中所示。
When you target Android 8.0 (API level 26), you must implement one or more notification channels to display notifications to your users.

所以,即使你使用了setVibrate(null)或其他变体,在26+版本中它将被忽略,因为该方法已被弃用,现在将使用NotificationChannel的模式:
/**
 * The pattern with which to vibrate.
 *
 * <p>
 * To vibrate the default pattern, see {@link #defaults}.
 * </p>
 *
 * @see android.os.Vibrator#vibrate(long[],int)
 * @deprecated use {@link NotificationChannel#getVibrationPattern()}.
 */
@Deprecated
public long[] vibrate;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接