Android燈光系統--通知燈深入分析
通知的類别
APP如何發出通知燈請求
- getSystemService(獲得通知服務)
- 構造notification
- 發出通知
系統如何處理
- 啟動通知Service
- 收到通知之後
- 對于通知燈
APP如何獲得通知服務
- ContextImp:resigsterService
- 傳回一個NotificationManager對象
- 構造Notification
- NotificationManager.notify()将通知發送出去
發送通知之後如何調用通知燈
- Service=getService() //獲得某個服務
- 注冊有Notification服務
- 根據名字Notification獲得Service服務
- Service.enqueueNotificationwithTag //放入通知隊列
- 通過enqueueNotificationwithTag中的buzzBeepBlinkLocked判斷是否是屬于哪種通知類别
- 獲得通知屬于閃燈,調用updateLightsLocked()
- 取出notification當中的參數,調用mNotificationLights類當中的setFlashing
- 注冊LightManager服務
- 根據ID從LightManager中傳回擷取mNotificationLights類
編寫模拟通知燈安卓程式
- 定義按鈕,控制20S之後熄屏亮燈
- 定義Flashing boolean型變量,用于控制按鈕操作
- 設定按鈕響應函數--判斷按鈕操作,改變按鈕text值,并且發出通知
- 構造通知執行方法 - 實作Runnable接口方法
- 調用開通知燈函數
- 獲得通知服務
- 構造通知,設定參數
- 發送通知
- 通知
附上詳細代碼:
package com.example.alienware.app_0002_lightdemo;
import android.app.Notification;
import android.app.NotificationManager;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
/*
* 模拟熄屏時候,短信等通知發生時候,通知燈亮起
* 設定螢幕背光亮時間為15s,才可以進行下列實驗
* Date:2017.2.16 Author:LKQ
* 代碼原創者:韋東山老師
*/
public class MainActivity extends AppCompatActivity {
private Button mLightButton = null;
boolean Flashing = false;
final private int LED_NOTIFICATION_ID = 109;
private Handler mLightHandler = new Handler();
private LightRunnable mLightRunnable = new LightRunnable();
//實作消息通知後的執行方法
class LightRunnable implements Runnable{
@Override
public void run() {
if(Flashing){
BlueFlashLight(); //藍燈閃亮
}
else{
ClearLED(); //關閉通知燈
}
}
}
private void BlueFlashLight()
{
NotificationManager nm = (NotificationManager)getSystemService( NOTIFICATION_SERVICE ); //擷取通知服務
Notification notif = new Notification(); //構造通知類型
notif.flags = Notification.FLAG_SHOW_LIGHTS; //設定通知類型為通知燈
notif.ledARGB = 0xFF0000ff; //顔色
notif.ledOnMS = 1000;
notif.ledOffMS = 1000; //閃爍時間為1S
nm.notify(LED_NOTIFICATION_ID, notif); //發送通知
}
private void ClearLED()
{
NotificationManager nm = ( NotificationManager ) getSystemService( NOTIFICATION_SERVICE );
nm.cancel( LED_NOTIFICATION_ID ); //關閉通知燈
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLightButton = (Button)findViewById(R.id.button);
mLightButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Flashing = !Flashing;
if (Flashing) {
mLightButton.setText("Stop Flashing the Light !");
} else {
mLightButton.setText("Flashing Light at 20S");
}
mLightHandler.postDelayed(mLightRunnable, 20000); //20S之後,即是熄屏時候,通知燈閃爍
}
});
}
}