Ionic+cordova Real-time notification alerting function based on websocket implementation _ionic

Source: Internet
Author: User

The app receives background-issued requests and prompts the user with a new message through the status bar, here the first thing to solve is how the front and back end of the interconnection, such as the PC end of the application, will generally use the front-end timing request backstage, but if the app to visit the background, the user is not friendly, this will consume a lot of users of mobile traffic, The best way to move the end is to push the information to the app in the background, H5 provides a better way is websocket, users open the app, to the background to send a request, after the background, you can immediately push the message to the front, and without the app to visit again, the specific front and rear platform to achieve the following:

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 {//static variable, used to record the current number of online connections.
    It should be designed to be thread-safe.
     
    private static int onlinecount = 0; The thread-safe set of the concurrent package, which holds the corresponding Mywebsocket object for each client. To enable the server to communicate with a single client, you can use a map to store the key that can be identified by the user as private static copyonwritearrayset<websocket> Websocketset = new Copy
     
    Onwritearrayset<websocket> ();
     
    A connection session with a client, which needs to be sent to the client to send the data private sessions; /** * Connection establishes a successful invocation method * @param session optional parameter. Session for a connection to a client, you need to send the data to the client/@OnOpen public void OnOpen {this.session = ses
        Sion Websocketset.add(this);           Add Addonlinecount () to the set; Online number plus 1 System.out.println ("There is a new join.")
    Current online number is "+ Getonlinecount ()");  /** * Connection Shutdown method of call/@OnClose public void OnClose () {websocketset.remove (this);           Deletes the Subonlinecount () from the set; Number of online minus 1 System.out.println ("There is a connection closed.")
    Current online number is "+ Getonlinecount ()");
    /** * The method called after receiving client messages * @param message client Sent messages * @param session Optional Parameters * * @OnMessage
         
        public void OnMessage (String messages, session sessions) {SYSTEM.OUT.PRINTLN ("Message from client: ' +"); Mass message for (WebSocket Item:websocketset) {try {item.sendmessage (
            message);
                catch (IOException e) {e.printstacktrace ();
            Continue /** * @param session * @param error/@OnError public v when an error occurs OID OnError (Session session, Throwable error) {System.out.println ("error occurred");
    Error.printstacktrace (); /** * This method is not the same as the above methods.
     Without annotations, it is based on the method you need to add.
        * @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--; }    
}

The code requested in app is as follows:

WebSocket = null;

var websocketaddress = ' ws://' + URL

//Determine if the current browser supports WebSocket
if (' WebSocket ' in window) {
    WebSocket = new WebSocket (websocketaddress);
}
else{
    alert (' not support WebSocket ')
}

//Connection Error callback method
Websocket.onerror = function () {
    // Notificationreminder ("error");

Connection successfully established callback method
Websocket.onopen = function (event) {
    Console.log (event);
}

The callback method received for the message
websocket.onmessage = function (event) {
    $scope. Notificationreminder (Event.data);
}

The callback method for connection shutdown
websocket.onclose = function () {
    //notificationreminder ("close");
}

Listen to the window Shutdown event, when the window is closed, active to close the WebSocket connection, to prevent the connection has not been disconnected to close the window, the server side will throw an exception.
window.onbeforeunload = function () {
    websocket.close ();
}

Send Message
$scope. Send = function () {
    websocket.send (localstorageservice.get (' UserID '));
$scope. Closewebsocket = function () {
    websocket.close ();
}


After the success of the front-end interconnection, to do is the front end to receive information from the background, how to display in the status bar, prompting the user, here is mainly used to provide Plug-ins Cordova, first installed Cordova-plugin-local-notifications, Then in the JS configuration can be as follows:

Status bar notification reminder
$scope. Notificationreminder = function (faxinfo) {
    Cordova.plugins.notification.local.add ({  
        ID : ID,
        title: ',  
        text: ',  
        at:new Date (). GetTime (),  
        //badge:2,  
        autoclear:true,//default  
        sound: ' Res://platform_default ',//default value  
        icon: ' Res://ic_popup_reminder ',///default value  
        ongoing:false  //default value  
    });


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: