ionic+cordova基於websocket實現的即時通報提醒功能_ionic

來源:互聯網
上載者:User

app接收後台發出的請求,並通過狀態列提示使用者有新的訊息,這裡首先要解決的就是前後端如何互聯,像pc端的應用,一般會採用前端定時請求後台,但如果要app定時去訪問背景話,對使用者來說並不友好,這會消耗使用者大量的移動流量,移動端最好的方式就是後台主動向app推送資訊,h5提供了一種比較好的方式就是websocket,使用者開啟app後,向後台發出請求,後台相應後,就可以即時向前端推送資訊了,而無需app再次去訪問,具體前後台實現如下:

package com.wavefax.wavefax51.openapi.servlet;import java.io.IOException;import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;/** * * @author Administrator */@ServerEndpoint("/websocket")public class WebSocket {    //靜態變數,用來記錄當前線上串連數。應該把它設計成安全執行緒的。    private static int onlineCount = 0;         //concurrent包的安全執行緒Set,用來存放每個用戶端對應的MyWebSocket對象。若要實現服務端與單一用戶端通訊的話,可以使用Map來存放,其中Key可以為使用者標識    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();         //與某個用戶端的串連會話,需要通過它來給用戶端發送資料    private Session session;         /**     * 串連建立成功調用的方法     * @param session  可選的參數。session為與某個用戶端的串連會話,需要通過它來給用戶端發送資料     */    @OnOpen    public void onOpen(Session session){        this.session = session;        webSocketSet.add(this);     //加入set中        addOnlineCount();           //線上數加1        System.out.println("有新串連加入。當前線上人數為" + getOnlineCount());    }         /**     * 串連關閉調用的方法     */    @OnClose    public void onClose(){        webSocketSet.remove(this);  //從set中刪除        subOnlineCount();           //線上數減1            System.out.println("有一串連關閉。當前線上人數為" + getOnlineCount());    }         /**     * 收到用戶端訊息後調用的方法     * @param message 用戶端發送過來的訊息     * @param session 可選的參數     */    @OnMessage    public void onMessage(String message, Session session) {        System.out.println("來自用戶端的訊息:" + message);                 //群發訊息        for(WebSocket item: webSocketSet){                         try {                item.sendMessage(message);            } catch (IOException e) {                e.printStackTrace();                continue;            }        }    }         /**     * 發生錯誤時調用     * @param session     * @param error     */    @OnError    public void onError(Session session, Throwable error){        System.out.println("發生錯誤");        error.printStackTrace();    }         /**     * 這個方法與上面幾個方法不一樣。沒有用註解,是根據自己需要添加的方法。     * @param message     * @throws IOException     */    public void sendMessage(String message) throws IOException{        this.session.getBasicRemote().sendText(message);        //this.session.getAsyncRemote().sendText(message);    }     public static synchronized int getOnlineCount() {        return onlineCount;    }     public static synchronized void addOnlineCount() {        WebSocket.onlineCount++;    }         public static synchronized void subOnlineCount() {        WebSocket.onlineCount--;    }    }

在app發請求的代碼如下:

websocket = null;var websocketAddress = 'ws://'+ url//判斷當前瀏覽器是否支援WebSocketif('WebSocket' in window){    websocket = new WebSocket(websocketAddress);}else{    alert('Not support websocket')}//串連發生錯誤的回調方法websocket.onerror = function(){    //notificationReminder("error");};//串連成功建立的回調方法websocket.onopen = function(event){    console.log(event);}//接收到訊息的回調方法websocket.onmessage = function(event){    $scope.notificationReminder(event.data);}//串連關閉的回調方法websocket.onclose = function(){    //notificationReminder("close");}//監聽視窗關閉事件,當視窗關閉時,主動去關閉websocket串連,防止串連還沒斷開就關閉視窗,server端會拋異常。window.onbeforeunload = function(){    websocket.close();}//發送訊息$scope.send = function(){    websocket.send(localStorageService.get('UserID'));}$scope.closeWebSocket = function(){    websocket.close();}


前後端互聯成功後,要做就是前端接收到後台發來的資訊後,如何顯示在狀態列上,提示使用者,這裡主要用到cordova提供的外掛程式,首先安裝cordova-plugin-local-notifications,然後在js配置好如下就可以了:

狀態列通報提醒$scope.notificationReminder = function(faxInfo){    cordova.plugins.notification.local.add({          id: id,        title: '',          text: '',          at: new Date().getTime(),          //badge: 2,          autoClear: true,//預設值          sound: 'res://platform_default',//預設值          icon: 'res://ic_popup_reminder', //預設值          ongoing: false  //預設值      });} 


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.