本文转自:http://intown.biz/2014/04/11/android-notifications/

ANDROID NOTIFICATIONS USING CORDOVA AND IONIC

So you want to add push notifications to your Cordova/Android/Ionic app? I’ll walk through it. Most of this entry applies to Cordova and Android, in case you’ve made the mistake of NOT using Ionic…

Basic Info

Android notifications work through Google GCM (Google Cloud Messaging). You can read the details at http://developer.android.com/google/gcm/index.html, but here’s the summary:

Here’s the narrative version:  When your application starts up, the Android device registers with GCM server, which responds with a Registration ID.   The device then sends the registration ID to our Message Server, which stores it for future use.  Other information, such as the user’s name or location, can be sent for message targeting.

When we want to send out a notification, our Message Server sends the text to the GCM server, along with the registration ID and the API .  The GCM server relays info to the device.

The GCM Server

Setting up your Google GCM server should be a fairly quick process. It’s a simple mechanism from our perspective, but does a lot of the heavy lifting for us. Follow these directions to get it running: http://developer.android.com/google/gcm/gs.html. Be sure to make note of your GCM Project ID, and your API Key. The Project ID will go into your Android app configuration, for registration. The API Key is used to send notifications.

The Notification Server

There are any number of ways to do this, and from what I’ve seen, folks often use custom code for this. Of coruse there are some off the shelf products. But for development, I recommend the node-gcm project https://github.com/ToothlessGear/node-gcm. It’s a super-simple way to communicate with the GCM server. First install

npm install node-gcm

Next set up a node script similar to this one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var gcm = require('node-gcm');
var message = new gcm.Message();
 
//API Server Key
var sender = new gcm.Sender('INSERT_YOUR_API_SENDER_KEY_HERE');
var registrationIds = [];
 
// Value the payload data to send...
message.addData('message', "Hello Cordova!");
message.addData('title','Push Notification Sample' );
message.addData('msgcnt','2'); // Shows up in the notification in the status bar
message.addData('soundname','beep.wav'); //Sound to play upon notification receipt - put in the www folder in app
message.collapseKey = 'demo';
message.delayWhileIdle = true; //Default is false
message.timeToLive = 3000;// Duration in seconds to hold in GCM and retry before timing out. Default 4 weeks (2,419,200 seconds) if not specified.
 
// At least one reg id required
registrationIds.push('THIS_IS_THE_REGISTRATION_ID_THAT_WAS_GENERATED_BY_GCM');
 
/**
 * Parameters: message-literal, registrationIds-array, No. of retries, callback-function
 */
sender.send(message, registrationIds, 4, function (err, result) {
    console.log(result);
});

The Android App

As you know by now, you need a plugin to do just about anything in Cordova. So install the PushPlugin https://github.com/phonegap-build/PushPlugin. This should be the only plugin you need
for both Android and iOS. You might want to scan the instructions, but (as of now) they are both overly complicated and incomplete. For starters, you don’t need PlugMan to install. Just use:

cordova plugin add https://github.com/phonegap-build/PushPlugin.git

The coding was a little bit tricky, but I finally managed a functional script for Ionic notifications. See inline comments for more information on what’s going on here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//factory for processing push notifications.
angular.module('pushnotification', [])
   .factory('PushProcessingService', function() {
        function onDeviceReady() {
            console.info('NOTIFY  Device is ready.  Registering with GCM server');
            //register with google GCM server
            var pushNotification = window.plugins.pushNotification;
            pushNotification.register(gcmSuccessHandler, gcmErrorHandler, {"senderID":gcmAppID,"ecb":"onNotificationGCM"});
        }
        function gcmSuccessHandler(result) {
            console.info('NOTIFY  pushNotification.register succeeded.  Result = '+result)
        }
        function gcmErrorHandler(error) {
            console.error('NOTIFY  '+error);
        }
        return {
            initialize : function () {
                console.info('NOTIFY  initializing');
                document.addEventListener('deviceready', onDeviceReady, false);
            },
            registerID : function (id) {
                //Insert code here to store the user's ID on your notification server.
                //You'll probably have a web service (wrapped in an Angular service of course) set up for this.
                //For example:
                MyService.registerNotificationID(id).then(function(response){
                    if (response.data.Result) {
                        console.info('NOTIFY  Registration succeeded');
                    } else {
                        console.error('NOTIFY  Registration failed');
                    }
                });
            },
            //unregister can be called from a settings area.
            unregister : function () {
                console.info('unregister')
                var push = window.plugins.pushNotification;
                if (push) {
                    push.unregister(function () {
                        console.info('unregister success')
                    });
                }
            }
        }
    });
 
// ALL GCM notifications come through here.
function onNotificationGCM(e) {
    console.log('EVENT -> RECEIVED:' + e.event + '');
    switch( e.event )
    {
        case 'registered':
            if ( e.regid.length > 0 )
            {
                console.log('REGISTERED with GCM Server -> REGID:' + e.regid + "");
 
                //call back to web service in Angular.
                //This works for me because in my code I have a factory called
                //      PushProcessingService with method registerID
                var elem = angular.element(document.querySelector('[ng-app]'));
                var injector = elem.injector();
                var myService = injector.get('PushProcessingService');
                myService.registerID(e.regid);
            }
            break;
 
        case 'message':
            // if this flag is set, this notification happened while we were in the foreground.
            // you might want to play a sound to get the user's attention, throw up a dialog, etc.
            if (e.foreground)
            {
                //we're using the app when a message is received.
                console.log('--INLINE NOTIFICATION--' + '');
 
                // if the notification contains a soundname, play it.
                //var my_media = new Media("/android_asset/www/"+e.soundname);
                //my_media.play();
                alert(e.payload.message);
            }
            else
            {
                // otherwise we were launched because the user touched a notification in the notification tray.
                if (e.coldstart)
                    console.log('--COLDSTART NOTIFICATION--' + '');
                else
                    console.log('--BACKGROUND NOTIFICATION--' + '');
 
                // direct user here:
                window.location = "#/tab/featured";
            }
 
            console.log('MESSAGE -> MSG: ' + e.payload.message + '');
            console.log('MESSAGE: '+ JSON.stringify(e.payload));
            break;
 
        case 'error':
            console.log('ERROR -> MSG:' + e.msg + '');
            break;
 
        default:
            console.log('EVENT -> Unknown, an event was received and we do not know what it is');
            break;
    }
}

Call it from here:

1
2
3
4
app.run(function(PushProcessingService) {
   //run once for the app
   PushProcessingService.initialize();
});

Hopefully this is helpful to someone!

Thanks to these folks (and others) who put together helpful blogs on this topic:

[转]ANDROID NOTIFICATIONS USING CORDOVA AND IONIC的更多相关文章

  1. Cordova+Angularjs+Ionic 混合开发入门讲解

    作为一名学习Android开发的学生,对于移动开发的发展趋势颇为关注,大家都知道,现在原生的移动开发在企业上基本很少使用了,大部分企业为了降低成本,选择了webapp,hybrid(混合开发)这两种模 ...

  2. 如何在android studio中cordova的混合开发

    基于Android Studio 中Cordova的开发 cordova简介 Cordova的前身是PhoneGap 官网: (http://cordova.io) Cordova应是运行在客户端本地 ...

  3. Cordova+angularjs+ionic+vs2015开发(三)

    欢迎加群学习:457351423 这里有4000多部学习视频,涵盖各种技术,有需要的欢迎进群学习! 一.基础设置 1.修改App名称和程序起始页 打开config.xml配置文件显示如下,在[通用]选 ...

  4. 【工具相关】ionic-通过nmp安装最新版本的 cordova 和 ionic

    一,命令行下输入: sudo npm install -g cordova ionic 用来安装最新版本的cordova和ionic. 如下图所示: 二,等待一下,如下图所示. 三,用命令 npm u ...

  5. Cordova+angularjs+ionic+vs2015开发(五)

    欢迎加群学习:457351423 这里有4000多部学习视频,涵盖各种技术,有需要的欢迎进群学习! 一.创建侧边菜单和导航项目 1.使用VS创建一个Ionic空项目,同时创建一个Ionic SideM ...

  6. Cordova+angularjs+ionic+vs2015开发(二)

    欢迎加群学习:457351423 这里有4000多部学习视频,涵盖各种技术,有需要的欢迎进群学习! 一.创建空白Cordova应用 打开VS,选择[新建项目],选择其它语言JavaScript或者Ty ...

  7. Android notifications通知栏的使用

    app发送通知消息到通知栏中的关键代码和点击事件: package com.example.notifications; import android.os.Bundle; import androi ...

  8. Cordova+angularjs+ionic+vs2015开发(四)

    欢迎加群学习:457351423 这里有4000多部学习视频,涵盖各种技术,有需要的欢迎进群学习! 一.布局 Ionic模板提供了一个侧边栏菜单示例项目和标签选项卡示例项目.本案例将两个布局进行结合, ...

  9. Cordova+angularjs+ionic+vs2015开发(一)

    欢迎加群学习:457351423 这里有4000多部学习视频,涵盖各种技术,有需要的欢迎进群学习! 一.Windows环境配置 1.如果已经安装VS2015,打开[工具]-[选项]找到Cordova选 ...

随机推荐

  1. IClient for js开发之地图的加载

    进行web开发之前首先需要安装IServer以及iClient for JavaScript的开发包.在这两中都具备的前提下进行第一步,如何调用IServer中发布的服务 调用iServer 中发布的 ...

  2. Croppic – 免费开源的 jQuery 图片裁剪插件

    Croppic 这款开源的 jQuery 图片裁剪插件能够满足网站开发人员各种不同的使用需要.只需要简单的上传图片,就可以实现你想要的图像缩放和裁剪功能.因为使用了 HTML5 FormData  对 ...

  3. css通用小笔记01——导航背景

    很多刚接触前端的可能遇到一些css能解决的小问题,我现在总结了一些,将会逐渐和大家分享,先是导航的背景问题,在网页中常常看到,当鼠标放到一个导航按钮上面是,就会出现一些特效,比如背景,这是最常用的,我 ...

  4. js一些代码方法

    概要 1.替换json对象中属性值(包括子对象) 2.兼容多个$库写法(zepto与jquery) 3.闭包保持变量的做法 详情 1.替换json对象中属性值(包括子对象) //替换json对象属性值 ...

  5. Spring(2) ------ 依赖注入

    spring框架为我们提供了三种注入方式,分别是set注入,构造方法注入,接口注入. 1.set注入: 采用属性的set方法进行初始化,就成为set注入. 1)给普通字符类型赋值. public cl ...

  6. 如何使用代码或脚本启用SharePoint的备用语言

    SP的多语言,需要安装语言包,然后手工去sharepoint下启动备用语言,如下图: [网站操作]-[语言设置]: 方法一:采用powershell处理 在很多项目情况下,需要用代码进行备用语言启动. ...

  7. CVE: 2014-6271、CVE: 2014-7169 Bash Specially-crafted Environment Variables Code Injection Vulnerability Analysis

    目录 . 漏洞的起因 . 漏洞原理分析 . 漏洞的影响范围 . 漏洞的利用场景 . 漏洞的POC.测试方法 . 漏洞的修复Patch情况 . 如何避免此类漏洞继续出现 1. 漏洞的起因 为了理解这个漏 ...

  8. 如何收缩超大的SharePoint_Config数据库

    前言 在已经运行了2年多的SharePoint服务器上,发现SharePoint_Config的数据库文件越来越大,已经达到90几个GB,收缩可以减小20几个GB,但是一周以后又会恢复到90几个GB大 ...

  9. Failed to connect to database. Maximum number of conections to instance exceeded

    我们大体都知道ArcSDE的连接数有 48 的限制,很多人也知道这个参数可以修改,并且每种操作系统能支持的最大连接数是不同的. 如果应用报错:超出系统最大连接数 该如何处理? 两种解决办法: 第一,首 ...

  10. 操作系统开发系列—4.LDT

    一直以来,我们把所有的段描述符都放在GDT中,而不管它属于内核还是用户程序,为了有效地在任务之间实施隔离,处理器建议每个任务都应当具有自己的描述符表,称为局部描述符表LDT,并且把专属于自己的那些段放 ...