【问题标题】:How can I enable vibration and lights using the Android notifications api?如何使用 Android 通知 API 启用振动和灯光?
【发布时间】:2012-12-25 15:16:29
【问题描述】:

我使用以下代码创建了一个创建通知的应用程序:

// notification
Notification notification = new Notification(R.drawable.notification_icon, title, System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;

// parameters
String ringtone = prefs.getString(context.getString(R.string.key_notifications_ringtone), "");
if (ringtone.length() > 0) {
    notification.sound = Uri.parse(ringtone);
    notification.audioStreamType = AudioManager.STREAM_NOTIFICATION;
}

boolean useVibrator = prefs.getBoolean(context.getString(R.string.key_notifications_use_vibrator), false);
if (useVibrator) {
    notification.defaults |= Notification.DEFAULT_VIBRATE;
}

boolean useLed = prefs.getBoolean(context.getString(R.string.key_notifications_use_led), false);
if (useLed) {
    notification.defaults |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
}

// alert
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification);
contentView.setImageViewResource(R.id.notification_icon, R.drawable.icon);
contentView.setTextViewText(R.id.notification_title, title);
contentView.setTextViewText(R.id.notification_text, text);
notification.contentView = contentView;

Intent notificationIntent = new Intent(context, MyActivity.class);

PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;

notificationManager.notify(1, notification);

通知有效,并且使用了正确的铃声。

但是,即使正确激活了首选项并且正确设置了通知标志(我通过调试进行了检查),通知也不会振动,也不会导致灯被激活。

我会责怪我手机的设置,但其他所有使用通知的应用程序,如消息、gmail 和其他应用程序都正确使用了所有这些功能。

有人知道我做错了什么吗? (我的手机是安卓2.1的HTC Hero)

【问题讨论】:

  • 你有震动权限吗?
  • 我在我的 Nexus One 上测试了你的代码,得到了许可,我确实得到了振动,但没有得到 LED...仍在挖掘
  • 同样的事情,我错过了振动许可,现在该部分正在工作。
  • @SirDarius :即使对我来说,灯也不起作用。你找到解决方案了吗?
  • 好吧,正如我在评论中所说,它确实在从接受的答案设置权限后开始工作。

标签: android notifications


【解决方案1】:

为您的清单文件添加权限

<uses-permission android:name="android.permission.VIBRATE"></uses-permission>

编辑

对于灯光,请尝试显式添加它们,默认灯光可能配置为 nolight

notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.ledARGB = 0xff00ff00;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;

【讨论】:

  • 我也建议过,但想了想,不可能。当您没有权限时,应用程序崩溃不是吗?这样他就不会看到其余的工作了
  • 我也是这么想的,权限缺失应该会抛出异常。
  • 完成我之前的评论,添加缺少的权限就可以了,但是仍然没有灯,我没有找到用于该目的的特定权限
  • 好的,我接受这个答案,因为出于某种原因,在不更改代码的情况下,即使无需指定非默认 LED 方案,灯现在也可以工作。
  • 我使用的是 Nexus 5,但指示灯不显示。你做了什么?有人吗?
【解决方案2】:

除了Pentium10的回答:

让您的设备进入睡眠状态,灯会亮起! ;)

【讨论】:

  • Hello OneWorld 试试上面的代码并将这段代码也放在 note.defaults |= Notification.DEFAULT_SOUND; note.defaults |= Notification.DEFAULT_VIBRATE;通过这种方式,振动和声音有效,但即使我将设备置于睡眠状态,灯光也不工作,灯光会熄灭。
  • 对于将来遇到这种情况的任何人,请确保按照 OneWorld 所说的那样关闭手机。还要确保通知托盘尚未被拉下(即用户尚未查看通知)。 LED 只会在这种情况下闪烁。
猜你喜欢
  • 1970-01-01
  • 2017-01-14
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-31
相关资源
最近更新 更多