Android 如何有 LED 灯通知?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10402686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:34:56  来源:igfitidea点击:

How to have LED Light Notification?

android

提问by Cameron McBride

Update: I am reworking the original post for compatibility before Android 3.0.

更新:我正在修改原始帖子以在 Android 3.0 之前兼容。

I am trying to create a simple notification and everything but the light works great. I do have the screen off when the notification fires. Using this deprecated code sound and vibrations works on Android 4.0 (Galaxy Nexus) and Android 2.3 (HTC EVO).

我正在尝试创建一个简单的通知,但除灯外的所有内容都很好用。当通知触发时,我确实关闭了屏幕。使用此弃用代码声音和振动适用于 Android 4.0 (Galaxy Nexus) 和 Android 2.3 (HTC EVO)。

  • On the 2.3 HTC EVO the lights also work.
  • On the 4.0 Galaxy Nexus the lights do not work.

    Notification notification = 
            new Notification(R.drawable.ic_launcher, "My Ticker!",System.currentTimeMillis());
    notification.setLatestEventInfo(context, "My Title", "My Message", pendingIntent);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    
    //notification.defaults |= Notification.DEFAULT_LIGHTS;
    
    notification.ledARGB = 0xff00ff00;
    notification.ledOnMS = 300;
    notification.ledOffMS = 1000;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    
  • 在 2.3 HTC EVO 上,灯也可以工作。
  • 在 4.0 Galaxy Nexus 上,灯不工作。

    Notification notification = 
            new Notification(R.drawable.ic_launcher, "My Ticker!",System.currentTimeMillis());
    notification.setLatestEventInfo(context, "My Title", "My Message", pendingIntent);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    
    //notification.defaults |= Notification.DEFAULT_LIGHTS;
    
    notification.ledARGB = 0xff00ff00;
    notification.ledOnMS = 300;
    notification.ledOffMS = 1000;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    

I have also tried newer APIs that are not part of the v4 compatibility library, so I could only test this on the Galaxy Nexus. Vibration and Sound works again but not lights.

我还尝试了不属于 v4 兼容性库的较新 API,因此我只能在 Galaxy Nexus 上进行测试。振动和声音再次起作用,但灯光不起作用。

Notification.Builder builder = new Notification.Builder(context);
        builder.setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("My Ticker")
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND | Notification.FLAG_SHOW_LIGHTS)
            .setLights(0xff00ff00, 300, 100)
            .setContentTitle("My Title 1")
            .setContentText("My Text 1");
        Notification notification = builder.getNotification();

I have now tested this on two stock Galaxy Nexus phones and the light works on neither. The screen IS off when I run the tests and all other apps on the phones trigger the lights without issue.

我现在已经在两部库存的 Galaxy Nexus 手机上测试了这个,但两者都没有。当我运行测试时屏幕关闭,手机上的所有其他应用程序都没有问题地触发灯。

回答by Drake Clarris

If you use setDefaults(DEFAULT_LIGHTS) or setDefaults(DEFAULT_ALL), it will ignore FLAG_SHOW_LIGHTS and any calls to setLights(). I found that on my phone, the defaults would not light up anything. So do not use DEFAULT_ALL or DEFAULT_LIGHTS, and play with the RGB color if necessary... although 0xff00ff00 should work in pretty much all cases.

如果您使用 setDefaults(DEFAULT_LIGHTS) 或 setDefaults(DEFAULT_ALL),它将忽略 FLAG_SHOW_LIGHTS 和任何对 setLights() 的调用。我发现在我的手机上,默认设置不会点亮任何东西。所以不要使用 DEFAULT_ALL 或 DEFAULT_LIGHTS,如有必要,请使用 RGB 颜色……尽管 0xff00ff00 几乎适用于所有情况。

回答by raj

The LED works when the device is turned off (not powered off :P). To test write a simple app to create notification with delay and during the delay turn off the phone and wait to see the LED blink.

LED 在设备关闭时工作(未关闭电源:P)。要测试编写一个简单的应用程序来创建延迟通知,并在延迟期间关闭手机并等待 LED 闪烁。

回答by bipin

Came across this today..if its still useful... Only certain notifications with a priority - HIGH,MAX will be able to cause the LED to glow, while those with lower priority LOW,MIN should not. Adding this should make the LED glow...

今天遇到了这个......如果它仍然有用......只有具有优先级的某些通知 - HIGH,MAX 将能够导致 LED 发光,而那些具有较低优先级的 LOW,MIN 不应该。添加这个应该会使 LED 发光......

builder.setPriority(Notification.PRIORITY_MAX)

builder.setPriority(Notification.PRIORITY_MAX)

回答by Martin Pfeffer

4 the lazy people:

4、懒人:

private void testNotification() {
    Notification.Builder builder = new Notification.Builder(this);
    builder.setSmallIcon(R.drawable.ic_launcher)
        .setPriority(Notification.PRIORITY_HIGH)
        .setOngoing(true);
    builder.setLights(0xff00ff00, 300, 100);
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(1, builder.build());
}

回答by Hal Cheung

I have tried my code below, and it works fine for me. My mobile is Nexus 6P:

我在下面尝试了我的代码,它对我来说很好用。我的手机是 Nexus 6P:

mBuilder.setContentTitle("APP_NAME")
                .setContentText(msg)
                .setContentIntent(PendingIntent.getActivity(mCtxt, UUID.randomUUID().hashCode(), new Intent(mCtxt, ReceivePushActivity.class), Notification.FLAG_AUTO_CANCEL))
                .setWhen(System.currentTimeMillis())
                .setPriority(Notification.PRIORITY_DEFAULT)
                .setAutoCancel(true)
                //.setDefaults(Notification.DEFAULT_ALL)
                .setVibrate(new long[] {0, 1000, 200,1000 })
                .setLights(Color.MAGENTA, 500, 500)
                .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                .setSmallIcon(R.mipmap.notify_logo);

        Notification ntf = mBuilder.build();
//        ntf.flags = Notification.DEFAULT_ALL;
//        ntf.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
//        ntf.flags |= Notification.FLAG_AUTO_CANCEL;

        mNotificationManager.notify(notifyId, ntf);

Just remove all 'DEFAULT_ALL' settings.

只需删除所有“DEFAULT_ALL”设置。

回答by DroidDev

If you want to turn on the screen lights when a notification is received, I'd suggest using PowerManagerand WakeLock. Following is the code to turn on the screen using mentioned classes:

如果您想在收到通知时打开屏幕灯,我建议使用PowerManagerWakeLock。以下是使用提到的类打开屏幕的代码:

PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 
WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
                                 | PowerManager.ACQUIRE_CAUSES_WAKEUP
                                 | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();

NOTE: Don't forget to release the wakeLock using wakeLock.release();, otherwise the screen will remain turned on.

注意:不要忘记使用 释放唤醒锁wakeLock.release();,否则屏幕将保持打开状态。

P.S. User can also turn the screen off using lock button. I have done same in my app. I am not using wakeLock.release();and leave it to the user to turn off the screen.

PS 用户也可以使用锁定按钮关闭屏幕。我在我的应用程序中做了同样的事情。我不使用wakeLock.release();并将其留给用户关闭屏幕。

回答by pjsinc

I also fought with this for ages! Leds worked nicely in Samsung devices but on others, no luck at all. I finally found a solution though; setup listeners to screen on and off events:

我也为此奋斗了多年!Leds 在三星设备上运行良好,但在其他设备上,根本没有运气。不过,我终于找到了解决方案;设置监听器来屏蔽开和关事件:

registerReceiver(this.screenOnListener, new IntentFilter("android.intent.action.SCREEN_ON"));
registerReceiver(this.screenOffListener, new IntentFilter("android.intent.action.SCREEN_OFF"));

Then add set and cancel of the notification on those listeners:

然后在这些侦听器上添加设置和取消通知:

public class ScreenOffListener extends BroadcastReceiver
{
    public ScreenOffListener() {}

    public void onReceive(Context paramContext, Intent paramIntent)
    {
        Notification notif = new Notification();
        notif.ledARGB = "0xFFFF0000"; // Red
        notif.flags = Notification.FLAG_SHOW_LIGHTS;
        notif.ledOnMS = 200; 
        notif.ledOffMS = 200; 
        nm.notify(NOTIFICATION_ID, notif);
    }
}

public class ScreenOnListener extends BroadcastReceiver
{
    public ScreenOnListener() {}

    public void onReceive(Context paramContext, Intent paramIntent)
    {
        NotificationTest.nm.cancel(NOTIFICATION_ID);
    }
}   

Works for me now. For some strange reason the notification needs to be set at this time or the led doesn't work. Everything else in the notification works when set at anytime...

现在为我工作。出于某种奇怪的原因,此时需要设置通知,否则 LED 不起作用。通知中的其他所有内容在随时设置时都有效......

Note: the color and on/off times do not really work for at least for blinking leds. They are defined by HW and LPG (Led Pattern Generator) so that they work also in deep sleep when CPU is more or less off and so the patterns and colors supported depend on the HW you have. Most systems have only one blinking pattern and the colors might be reduced to full on full off R, G and B (and combinations). For fully lit leds all colors seem to be available.

注意:颜色和开/关时间至少对闪烁的 LED 不起作用。它们由 HW 和 LPG(LED 模式发生器)定义,因此当 CPU 或多或少关闭时,它们也可以在深度睡眠中工作,因此支持的模式和颜色取决于您拥有的硬件。大多数系统只有一种闪烁模式,在完全关闭 R、G 和 B(以及组合)时,颜色可能会减少到完整。对于完全点亮的 LED,所有颜色似乎都可用。

回答by Ibrahim

.SetLights (Color.Red.ToAndroid (), 300, 300)

回答by Andrey

Add default Notification.DEFAULT_LIGHTS.

添加默认 Notification.DEFAULT_LIGHTS。

Example:

例子:

Notification notification = new NotificationCompat.Builder(baseCtx)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(body)
            .setDefaults(
                      Notification.DEFAULT_SOUND
                    | Notification.DEFAULT_VIBRATE
                    | Notification.DEFAULT_LIGHTS
            )
            .build();