How i can send notifications when my app is closed in Ionic?

前端 未结 1 1350
庸人自扰
庸人自扰 2021-01-24 03:05

I\'m using Ionic for mobile dev, i\'m actually using LocalNotifications

Every 5 minutes i check in my server if have new question:

this.checkQuestions();         


        
1条回答
  •  清酒与你
    2021-01-24 03:50

    If your user kill the app you can not make sure your user keep your app active. But if you really want to try you can use this.

    The most efficient is to use Push Notifications. Your server can send notification to your app when new data will be stored.

    EDIT

    Server side you can run a function to send push notification with something like this :

    function sendGCM($message, $id) {
    
    
        $url = 'https://fcm.googleapis.com/fcm/send';
    
        $fields = array (
                'registration_ids' => array (
                        $id
                ),
                'data' => array (
                        "message" => $message
                )
        );
        $fields = json_encode ( $fields );
    
        $headers = array (
                'Authorization: key=' . "YOUR_KEY_HERE",
                'Content-Type: application/json'
        );
    
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, true );
        curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
    
        $result = curl_exec ( $ch );
        echo $result;
        curl_close ( $ch );
    }
    
    ?>
    

    Run this function each 5 minutes in php if you want but better when new data are stored.

    SOURCE

    And, Ionic side, you can execute a function to get your data when you catch a push notification. Somethink like this :

    import { Component } from '@angular/core';
    import { Platform } from 'ionic-angular';
    import { StatusBar, Splashscreen } from 'ionic-native';
    
    import { HomePage } from '../pages/home/home';
    import {
      Push,
      PushToken
    } from '@ionic/cloud-angular';
    
    @Component({
      templateUrl: 'app.html'
    })
    export class MyApp {
      rootPage = HomePage;
    
      constructor(platform: Platform, public push: Push) {
        platform.ready().then(() => {
          StatusBar.styleDefault();
          Splashscreen.hide();
    
          this.push.register().then((t: PushToken) => {
            return this.push.saveToken(t);
          }).then((t: PushToken) => {
            console.log('Token saved:', t.token);
          });
    
          this.push.rx.notification()
          .subscribe((msg) => {
            // CALL SERVE TO GET DATA
          });
        });
      }
    }
    

    SOURCE

    0 讨论(0)
提交回复
热议问题