呼吸灯是个非常酷的功能,闲暇之余就尝试做了这个。实现原理:利用android的通知指示灯,通过闹钟的方式实现呼吸灯。
俗话说“巧妇难为无米之炊”,我们的呼吸灯在那里呢?哈哈,就用android手机的通知指示灯。如何让led灯亮起来呢。利用发送通知的方式,相关代码如下:
private void showNotification() {
LogTool.d(TAG, "showNotification....");
if (mNotificationManager == null) {
mNotificationManager = (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
}
mNotificationManager.cancel(NOTIFICATION_ID);
Notification notice = new Notification();
notice.ledARGB= 0xff00ff00;
notice.ledOnMS = 1;
notice.ledOffMS = 0;
notice.flags |= Notification.FLAG_SHOW_LIGHTS;
Intent intent = new Intent();
PendingIntent des = PendingIntent.getActivity(this,
NOTIFICATION_REQUEST_CODE, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
notice.setLatestEventInfo(this, null, null, des);
mNotificationManager.notify(NOTIFICATION_ID, notice);
}
首先申请系统服务Activity.NOTIFICATION_SERVICE获得NotificationManager,然后创建一个不显示的Notification。让我们看看通知的相关参数: // 指示灯闪烁 notice.flags |= Notification.FLAG_SHOW_LIGHTS; //指示灯长亮 notice.ledOnMS = 1; notice.ledOffMS = 0; // 配置指示灯的颜色 notice.ledARGB= 0xff00ff00; 这里设置的指示灯的颜色为绿色,可以设置各种颜色实现五颜六色的led呼吸灯效果。 如何设置led灯有规律的闪烁呢。利用timer吗?,错了。在android手机锁屏后,Timer的就开始“墨迹”,定时效果不靠谱。理想的情况是使用闹铃功能,实现如下:
private void scheduleAlarm() {
LogTool.d(TAG, "scheduleAlarm....");
if (mAlarmManager == null) {
mAlarmManager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
}
// schedule notification
Intent intent = new Intent(INTENT_ACTION_SCHEDULE);
PendingIntent clock = PendingIntent.getBroadcast(this,
NOTIFICATION_REQUEST_CODE, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
mAlarmManager
.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
NOTIFICATION_ALARM_LENGTH, clock);
// schedule cancel notification
Intent cancelIntent = new Intent(INTENT_ACTION_CANCEL);
PendingIntent cancel = PendingIntent.getBroadcast(this,
NOTIFICATION_REQUEST_CODE, cancelIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + NOTIFICATION_LED_ONMS,
NOTIFICATION_ALARM_LENGTH, cancel);
}
首先我们获得了系统的闹钟服务Activity.ALARM_SERVICE,然后按固定间隔发送开启和关闭led的广播。 谁来收听我们的“天籁之音”呢?没有知音我们就创造一个:
private void startReceiver() {
if (mReceiver == null) {
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(INTENT_ACTION_SCHEDULE)) {
showNotification();
} else if (intent.getAction().equals(INTENT_ACTION_CANCEL)) {
LogTool.d(TAG, "cancel Notification....");
if (mNotificationManager != null) {
mNotificationManager.cancelAll();
}
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(INTENT_ACTION_CANCEL);
filter.addAction(INTENT_ACTION_SCHEDULE);
registerReceiver(mReceiver, filter);
}
}
点击此处下载源码
转载:http://www.adobex.com/android/source/details/00000237.htm