Push Notification (1)Google C2DM 服务

基于Google C2DM的消息推送

前提:

1. Android设备上有Google服务(可以在‘设置’->‘正在运行’中看到),并且设置了gmail帐号和同步。

2. 开发者需要注册gmail帐号,并且到 这里 注册一个应用。 (注册应用成功后,需要过几个小时才能生效)

3. android2.2及以上。

 

Server端流程:

1. 用开发者gmail帐号、密码登陆google,文档地址,登陆成功后,获取到了Token, Token可以保存一段时间,不必每次都登陆。

2. 用上面的Token,调用c2dm接口来给客户端发送消息,需要指定 Android设备的registration_id,这个id是在android客户端生成的,然后传给服务器端保存下来

Server Side
 1 package com.synnex.android;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.InputStreamReader;
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 
 8 import org.apache.http.HttpEntity;
 9 import org.apache.http.HttpResponse;
10 import org.apache.http.NameValuePair;
11 import org.apache.http.client.entity.UrlEncodedFormEntity;
12 import org.apache.http.client.methods.HttpPost;
13 import org.apache.http.impl.client.DefaultHttpClient;
14 import org.apache.http.message.BasicNameValuePair;
15 import org.apache.http.protocol.HTTP;
16 
17 public class Google
18 {
19     public static void main(String[] args) throws Exception
20     {
21 //        getToken();
22         sendMessage();
23     }
24     
25     /**
26      * first, get the auth-token, 
27      * the token is effective within a month, I think we should save the token
28      */
29     private static void getToken() throws Exception
30     {
31         DefaultHttpClient httpclient = new DefaultHttpClient();
32         HttpPost request = new HttpPost("https://www.google.com/accounts/ClientLogin");
33         List<NameValuePair> nvps = new ArrayList<NameValuePair>();
34         nvps.add(new BasicNameValuePair("accountType", "GOOGLE"));
35         nvps.add(new BasicNameValuePair("Email", "your@gmail.com"));
36         nvps.add(new BasicNameValuePair("Passwd", "*****"));
37         nvps.add(new BasicNameValuePair("service", "ac2dm"));
38         nvps.add(new BasicNameValuePair("source", "android_app_name-1.0"));
39         request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
40 
41         HttpResponse response = httpclient.execute(request);
42         HttpEntity entity = response.getEntity();
43 
44         System.out.println("Login form get: " + response.getStatusLine() + " , ");
45 
46         BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
47         String str = null;
48         while ((str = reader.readLine()) != null)
49         {
50             System.out.println(str);
51         }
52     }
53     
54     /**
55      * second, send message to android client
56      */
57     private static void sendMessage() throws Exception
58     {
59         DefaultHttpClient httpclient = new DefaultHttpClient();
60         HttpPost request = new HttpPost(
61                 "https://android.apis.google.com/c2dm/send");
62         List<NameValuePair> nvps = new ArrayList<NameValuePair>();
63         
64         // this is the client's identity id
65         nvps.add(new BasicNameValuePair("registration_id", "APA91bGg7Ifi3PKcehXL2IdI_U0Ivxs_wZ_RXE6BsX9HHwD73v_HNpY4PWrzHG6-OG56wcXeuCRI8vGAeupcCu2ecquI9upWSpW_A7S4vpHQOYVs4Hw1SLGnEQiGIyX34QlQgFkhnRhyaS54L8dXEyEzWyu6hrwNZg"));
66         nvps.add(new BasicNameValuePair("collapse_key", "6"));
67         
68         // this message will send to client
69         nvps.add(new BasicNameValuePair("data.msg", "{\"data\":[{id: \"1\", eventId: \"1\", title: \"服务器push notification测试\"}, {id: \"2\", eventId: \"2\", title: \"服务器push notification测试2\"}, {id: \"3\", eventId: \"3\", title: \"服务器push notification测试3\"}, {id: \"4\", eventId: \"4\", title: \"服务器push notification测试4\"}],\"errorMessage\":\"\",\"status\":\"success\"}"));
70         request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
71         
72         // auth val is from getToken() method
73         request.addHeader("Authorization", "GoogleLogin auth=DQAAALsAAABx8-Ocgx-TAEue8zxENduU2XKb4xOoc6VavtcYJ32b_RMV9L7FRXEVj7qPm5PStSpaJx55Q8hCTpVbroMbiTYec1Vs9GDve0P2wYqSGpap51F1QVahN_9XRaKJzFSxsSLLkGxFR4ui-ze-iOoOQhuLtvlvJfj0RkhMH5RYTLDq7_PRKRD533fD7NkkBokPga_PKrWX1jBH0qOQ3YfU__7j54-QYohnqcd2auQKv3xH1UYB67STqPyswssXwyZA3AY");
74 
75         HttpResponse response = httpclient.execute(request);
76         HttpEntity entity = response.getEntity();
77 
78         System.out.println("Login form get: " + response.getStatusLine() + " , ");
79 
80         BufferedReader reader = new BufferedReader(new InputStreamReader(
81                 entity.getContent()));
82         String str = null;
83         while ((str = reader.readLine()) != null)
84         {
85             System.out.println(str);
86         }
87     }
88 }

 

用到的第3方jar: httpcore-4.0.1.jar, httpclient-4.0.3.jar, commons-logging-1.1.1.jar

 

Client流程:

1. 用开发者gamil帐号,启动一个service,来生成registration_id,传给服务器,(只需生成一次即可)

2. 上面的service会在后台执行,接收来自服务器端的数据。

代码(注意要修改C2DMBaseReceiver.SENDER_ID字段,为你的gamil开发者帐号)


 


 

posted on 2011-11-04 14:01  TroyZ  阅读(1019)  评论(0编辑  收藏  举报