2011-11-07 58 views
6

我试图打开LED通知,例如绿色。关闭屏幕,每5秒钟将该颜色更改为红色(绿色 - >红色,红色 - >绿色)。我想我已经做了所有事情:在一个服务中,我创建了一个执行方法来显示通知的计时器。每5秒更改一次LED通知的颜色

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次,但立即停止。我知道这个应用程序完全没用,但我只想让它工作:)。我想我将不得不使用AlarmManager和PendingIntent启动我的服务...明天我会尽力做到这一点。

回答

1

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

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

哦,另外,尝试设置notify.ledOffMS = 5000;

+0

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

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编程。我想我解决了我的问题。