每5秒更改LED通知的颜色。

6

我正在尝试打开LED通知,例如绿色。关闭屏幕,并每5秒将该颜色更改为红色(绿色->红色,红色->绿色)。 我认为我已经做了一切:在服务中创建了一个计时器,执行显示通知的方法。

public class LEDService extends Service
{
private boolean TimerStarted;
private Timer timer;
private NotificationManager myNotificationManager;
private long LastColor;

public TurnLedOn()
{
     Notification notify = new Notification();
     notify.flags |= Notification.FLAG_SHOW_LIGHTS;
     notify.LedOnMS = 500;
     notify.LedOffMS = 0;
     //I in other example I also used array of colors
     if (LastColor == 0x00FF00) notify.LedARGB = 0xFF0000; else notify.LedARGB = 0x00FF00;         
     LastColor = notify.LedARGB;
}

private MyTimerTask extends TimerTask
{
    @Override
    public void run()
    {
        TurnLedOn();
    }
}

@Override
public void OnCreate()
{
    TimerStarted = false;
    myNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
    if (TimerStarted == false)
    {
        timer = new Timer();
        timer.schedule(new MyTimerTask(), 0, 5000);
    }        
    return START_STICKY;
}

@Override
public IBinder onBind()
{
    return null;
}

@Override
public void onDestroy()
{
    timer.close();
}
}

问题是什么?LED灯不改变颜色......当我关闭屏幕时,颜色是绿色的,直到我再次打开屏幕并将其关闭。我希望启动此服务一次,关闭屏幕并看到LED灯改变颜色:)。
顺便说一句:我测试了我的手机,它可以显示绿色和红色的灯光,所以这不是问题。
预先感谢您,对我的英语感到抱歉。
我不能回答自己的问题,所以我会在这里添加:
感谢您的建议Olsavage,我在我的代码中添加了clearAll(),但效果仍然相同;/。我还在我的应用程序中添加了日志记录(Log.i())。看起来像是系统在关闭屏幕时停止了我的服务(为什么?)。它是这样的:
屏幕已打开: 计时器正在运行,并且通知已部署(但我看不到灯亮,因为要看到它,必须关闭屏幕:P)
单击锁定按钮: 计时器几乎停止,因此LED有时会改变颜色一次。
屏幕已关闭: 计时器不工作,TurnLedOn方法不再运行。 LED不改变颜色。
现在的问题是:为什么在关闭屏幕后停止我的服务?即使我在其中执行简单的操作(如递增变量)。也许我需要设置其优先级或其他什么?
我将计时器间隔更改为100ms并查看代码是好的。 LED的颜色改变了5-15次,但随后立即停止。我知道这个应用程序完全没有用,但我只想让它工作:)。
编辑2: 我想我将不得不使用AlarmManager和PendingIntent来启动我的服务......明天我会尝试做到这一点。
2个回答

2

好的,我想我弄清楚了。完全删除了计时器。相反,我使用AlarmManager :).

我在onCreate中添加了以下代码:

alarmmgr = (AlarmManager) getSystemService(ALARM_SERVICE);

在onStartCommand方法中:

public int onStartCommand(Intent intent, int flags, int startId) 
{
 TurnLedOn();   //Turn LED On
 myPendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent. FLAG_UPDATE_CURRENT);   
 alarmmgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, myPendingIntent); //Setting alarm to be off after 5seconds.
 return Service.START_NOT_STICKY;
}

在onDestroy方法中:

public void onDestroy() 
{
notifymgr.cancel(LED_NOTIFICATION_ID);  //Clearing notification
alarmmgr.cancel(myPendingIntent);   //Clear alarm
}

我认为代码没有问题,但是我完全是Android编程的初学者。我认为我解决了我的问题。


1

你需要使用ARGB格式。尝试设置0xFFFF0000 - 红色和0xFF00FF00 - 绿色。希望这可以帮到你。

嗯,也许你的旧通知没有清除?在myNotificationManager.notify(0, notify);之前尝试使用myNotificationManager.clearAll();

哦,还有,尝试设置notify.ledOffMS = 5000;


它已经显示了正确的颜色 :) 问题是,当屏幕关闭时它不会改变颜色。为了改变颜色,我必须关闭手机屏幕并将其打开... 我想自动改变颜色。 - krzysnick

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