procedure TMainDataModule.SendNotification(const ATitle, AAlertBody, AData: string); var mNotice: TNotification; begin if NotificationCenter1.Supported then begin mNotice := NotificationCenter1.CreateNotification; try mNotice.Name := kbmMWGlobal.kbmMWGenerateGUID;//這里我用了唯一的名子,讓每條消息都是新的,如果用固定的名子,那么新消息來時會覆蓋舊的消息,即在消息欄中不會產生新的一條消息。 mNotice.Title := ATitle;//消息欄中的標題 mNotice.AlertBody := AAlertBody;//在消息欄中顯示的具體內容 mNotice.HasAction:=True; mNotice.AlertAction:=AData;//透傳的Json,業務邏輯可以通過Json來定義 // 通知 NotificationCenter1.PresentNotification(mNotice); finally mNotice.DisposeOf; end; end; end;
上面是一個通用的方法,客戶端調用,向app自己發出一個消息,為了接收這個消息,我們還要處理NotificationCenter1的OnReceiveLocalNotification事件:
procedure TForm10.NotificationCenter1ReceiveLocalNotification(Sender: TObject; ANotification: TNotification); begin //這里處理接收的消息 end;
為了更美觀,我們還要定義消息的圖標:
上圖,定義Notification的圖標。
如果你已經成為DPush的用戶,那上面的方法就不用我們去實現了,作者已經封裝了上面實現到DPush中,與DPush的處理邏輯合二為一,事情將變的簡單!
首先,通過TLeoDPushService.SendLocalNotification方法來為自己發送消息,下是是我進一步封裝到MainDataModule中的方法:
procedure TMainDataModule.SendLocalNotification(const ATitle, ASubject, AData: string); begin FPushService.SendLocalNotification(ATitle,ASubject,SO(AData),kbmMWGenerateGUID); end;
其次,接收消息時,自動觸發TLeoDPushService.OnGetPushDataEvent事件。與離線消息是一樣的,這非常爽了!關於收到離線消息的處理,可以參考前面寫的關於DPush的文章。