ionic3 消息推送

目录

 

1、插件使用

2、代码实现

3、真机测试

4、完整代码


  • 1、插件使用

1)推送插件:cordova.plugins.notification.local

插件安装:cordova plugin add cordova-plugin-local-notification

或者:cordova plugin add https://github.com/katzer/cordova-plugin-local-notifications.git

git地址:https://github.com/katzer/cordova-plugin-local-notifications

2)ng2-STOMP-Over-WebSocket插件 用于和后台通信

扫描二维码关注公众号,回复: 2682970 查看本文章

插件安装:npm i --save stompjs   npm i --save sockjs-client   npm i --save ng2-stomp-service

git地址:https://github.com/devsullo/ng2-STOMP-Over-WebSocket

  • 2、代码实现

1)推送代码实现

 clickObj = {};
  /**
   * @函数名称:sentInfo
   * @param
   * @作用:消息推送
   * @return:obj
   * @date 2018/7/19
   */
  sentInfo(item) {
    this.initLocalNotifications();
    const me = this;
    //新版本使用 add 可以替换 schedule
    const localNotifications = this.localNotifications;
    if (localNotifications.add) {
      localNotifications.add({
        id: item.charNum,
        title: item.text,
        text: item.label,
        at: item.at,
        badge: 2,
        sound: 'res://platform_default',//默认值
        icon: 'res://ic_popup_reminder', //默认值
        autoClear: true,//默认值
        ongoing: true,  //默认值
        data: item
      });
    } else {
      localNotifications.schedule({
        id: item.charNum,
        title: item.text,
        text: item.label,
        at: item.at,
        badge: 2,
        autoClear: true,//默认值
        ongoing: true,  //默认值
        data: item
      });
    }
    me.clickObj[item.charNum] = false;
    // 跳转到详情页面
    localNotifications.on('click', function(notification){
      // TODO 待优化 处理多次注入问题
      if (me.clickObj[notification.id]) {
        return;
      }
      if (!me.clickObj[notification.id]) {
        me.navCrt.push(EventInfoModal, notification.data);
      }
      me.clickObj[notification.id] = true;
    }, item.charNum);
  }

2)和后台对接代码实现

/**
   * @函数名称:stompFn
   * @param
   * @作用:websocket相关业务处理
   * @date 2018/7/19
   */
  stompFn() {
    //configuration
    const hostUrl = this.http.getUrl('/api/websocket');
    this.stomp.configure({
      host: hostUrl,
      debug: true,
      queue: {'init':false}
    });

    //start connection
    this.stomp.startConnect().then(() => {
      this.stomp.done('init');
      console.log("链接成功");
      //subscribe
      this.subscription = this.stomp.subscribe('/topic/subscribe', this.response);

      //send data
      // this.stomp.send('destionation',{"data":"data"});

      //unsubscribe
      // this.subscription.unsubscribe();

      //disconnect
      // this.stomp.disconnect().then(() => {
      //   console.log( 'Connection closed' )
      // })

    });
  }
  infoId = 0; // 消息id
  //response
  public response = (data) => {
    this.infoId++;
    const item = {
      img: 'data:image/jpeg;base64,' + data.checkJpg,
      text : this.getTitle(data),//single.checkName,
      label: this.getLabel(data),
      time: Number(data.time_norm),
      videoUrl: data.combiner_output_path+'/'+data.combiner_output_file+'/'+data.time+'.jpg.mp4',
      charNum: this.infoId
    };
    this.sentInfo(item);
  };
  • 3、真机测试

1)部署内网websocket连接不上

原因:host没有添加内网地址,正确连接地址例如 http://192.1.1.1:8888//api/websocket

切记订阅地址不需要添加http地址

this.stomp.configure({
               host: hostUrl,
               debug: true,
               queue: {'init':false}
           });

2)部署外网websocket连接不上

nginx配置问题

解决办法参考:http://www.cnblogs.com/duanweishi/p/9286461.html

  • 4、完整代码

import { HomePage } from '../home/home';
import { ListPage } from '../list/list';
import { Component, ViewChild, OnDestroy } from '@angular/core';
import { Nav, Platform, ModalController, NavController, Tabs } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { LoginPage } from '../login/login';
import { HttpSerProvider } from './../../providers/http-ser/http-ser';
import { BackButtonProvider } from "../../providers/back-button/back-button";
import { StompService } from 'ng2-stomp-service';
import { UtilsProvider } from './../../providers/utils/utils';
import { LoadingSerProvider } from '../../providers/loading-ser/loading-ser';
import { EventInfoModal } from '../home/eventInfoModal';

@Component({
  templateUrl: 'content.html'
})
export class ContentPage implements OnDestroy {
  @ViewChild(Nav) nav: Nav;
  @ViewChild('mytabs') mytabs: Tabs;
  pages: Array<{title: string, component: any}>;
  rootPage: any = HomePage;
  public subscription : any;
  constructor(
    public platform: Platform,
    public statusBar: StatusBar,
    public utils : UtilsProvider,
    public splashScreen: SplashScreen,
    public modalCtrl: ModalController,
    public http: HttpSerProvider,
    public navCrt: NavController,
    public backButtonService: BackButtonProvider,
    public stomp: StompService,
    public loading: LoadingSerProvider,
    ) {
    this.initializeApp();
    this.setPages();
    this.backFn();
    setTimeout(()=>{
      this.stompFn();
    });
  }
  // 注入home事件
  backFn() {
    this.platform.ready().then(() => {
      this.backButtonService.registerBackButtonAction(this.mytabs);
    });
  }
  /**
   * @函数名称:stompFn
   * @param
   * @作用:websocket相关业务处理
   * @date 2018/7/19
   */
  stompFn() {
    //configuration
    const hostUrl = this.http.getUrl('/api/websocket');
    this.stomp.configure({
      host: hostUrl,
      debug: false,
      queue: {'init':false}
    });

    //start connection
    this.stomp.startConnect().then(() => {
      this.stomp.done('init');
      //subscribe
      this.subscription = this.stomp.subscribe('/topic/subscribe', this.response);
      //send data
      // this.stomp.send('destionation',{"data":"data"});

      //unsubscribe
      // this.subscription.unsubscribe();

      //disconnect
      // this.stomp.disconnect().then(() => {
      //   console.log( 'Connection closed' )
      // })

    });
  }
  infoId = 0; // 消息id
  //response
  public response = (data) => {
    this.infoId++;
    const item = {
      img: 'data:image/jpeg;base64,' + data.checkJpg,
      text : this.getTitle(data),//single.checkName,
      label: this.getLabel(data),
      time: this.utils.timestampToTime(data.time_norm, null),
      at: Number(data.time_norm),
      videoUrl: data.combiner_output_path+'/'+data.combiner_output_file+'/'+data.time+'.jpg.mp4',
      charNum: this.infoId
    };
    this.sentInfo(item);
  };
  getLabel(single) {
    return this.utils.getDeviceNameLabel(single);
  }
  getTitle(single) {
    return this.utils.getDeviceNameTitle(single);
  }
  // 模块保存对象 将用到的对象保存下来
  localNotifications: any;
  initLocalNotifications() {
    if (!this.localNotifications) {
      this.localNotifications = cordova.plugins.notification.local;
    }
  }
  clickObj = {};
  /**
   * @函数名称:sentInfo
   * @param
   * @作用:消息推送
   * @return:obj
   * @date 2018/7/19
   */
  sentInfo(item) {
    this.initLocalNotifications();
    const me = this;
    //新版本使用 add 可以替换 schedule
    const localNotifications = this.localNotifications;
    if (localNotifications.add) {
      localNotifications.add({
        id: item.charNum,
        title: item.text,
        text: item.label,
        at: item.at,
        badge: 2,
        sound: 'res://platform_default',//默认值
        icon: 'res://ic_popup_reminder', //默认值
        autoClear: true,//默认值
        ongoing: true,  //默认值
        data: item
      });
    } else {
      localNotifications.schedule({
        id: item.charNum,
        title: item.text,
        text: item.label,
        at: item.at,
        badge: 2,
        autoClear: true,//默认值
        ongoing: true,  //默认值
        data: item
      });
    }
    me.clickObj[item.charNum] = false;
    // 跳转到详情页面
    localNotifications.on('click', function(notification){
      // TODO 待优化 处理多次注入问题
      if (me.clickObj[notification.id]) {
        return;
      }
      if (!me.clickObj[notification.id]) {
        me.navCrt.push(EventInfoModal, notification.data);
      }
      me.clickObj[notification.id] = true;
    }, item.charNum);
  }
  /**
   * @函数名称:setPages
   * @param
   * @作用:设置模块menu
   * @return:obj
   * @date 2018/7/20
   */
  setPages() {
    // used for an example of ngFor and navigation
    this.pages = [
      { title: '预警事件', component: HomePage },
      { title: '预警统计', component: ListPage }
    ];
  }
  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }

  /**
   * 菜单项打开
   * @param page
   */
  openPage(page) {
    // Reset the content nav to have just this page
    // we wouldn't want the back button to show in this scenario
    this.nav.setRoot(page.component);
  }

  /**
   * 退出登录
   */
  logOut() {
    this.http.clearToken();
    this.navCrt.push(LoginPage);
    // let modal = this.modalCtrl.create(LoginPage);
    // modal.present();
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

猜你喜欢

转载自blog.csdn.net/ligaoming_123/article/details/81116302