2

我正在Google Cloud Messaging (GCM) 上创建一个项目,并且正在关注本教程

我完成了客户端工作并在客户端设置了设备。我还使用以下代码注册了设备。

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);
    final String regId = GCMRegistrar.getRegistrationId(this);
    if (regId.equals("")) {
        GCMRegistrar.register(this, "483910217912");
        Log.d(tag, "Registered");
    }
    else {
        Log.v(tag, "Already registered");
    }
}

现在我被困在为我的 GCM 项目创建服务器的地方。请注意,我正在创建一个项目以在收到新消息时进行通知。不过,我还没有实现接收消息的服务,但我会在服务器设置完成后实现它。

4

6 回答 6

6

您可以使用博客文章Google 云消息传递 (GCM) 教程在 Android 中创建 GCM 服务器,但我更喜欢将PHP用于服务器端代码。您可以通过简单的步骤在cURL (PHP) 中创建 GCM 服务器:

  1. 从 Google API 控制台页面创建服务器密钥。

  2. 识别向其发送此消息的设备的设备令牌。

您可以在How to implement a GCM PHP push server for Android中找到简单的步骤来实现推送服务器。

于 2012-10-11T10:06:10.040 回答
5

你可以使用这个代码

package yourpackage.android.gcm.server;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;

import java.util.ArrayList;

class Notify {
    public static void main(String args[]) {

        try {

            Sender sender = new Sender("AIzaSyCn3N2OIm-EDtiGwTyQfSIB8NRvDtIOx30");

            ArrayList<String> devicesList = new ArrayList<String>();
//add you deviceID
            devicesList.add("APA91bELVJbxB_NLnLbTkkkX87SDdkJc6OfCN2slhC9t4cLq-KA32eGgiW4-Gi--ZEsEMKIh0AtYJMs5rQGswfm3cH1qK853WcpV98bkaplAaC5AiycDmifuVFSRl21vgf-Rqj0dCrFF");
                        //devicesList.add("APA91bHIdM4XGqrjJLTuwCX5OOrTYG4ACXYEVkZDM1bPs5qFdzJP4Bpql-sZqyKB8BU7fDtdxB84aTygHLyASYg_XNY6lqrcA4wj4sZHJXGVFzz_0UEADMfFCx9NAfRZxunIYso_dkBa");
            //APA91bFA-i2l3iEMnIBs0JK80pTLHOsE7p1s-DysRpKGas1MQOVILyIs9xwY7soysSWGz5Uif68uXR6F5Xn0tCTYesv78uQZxhC310a1cvf8aFohhfMGY6awbOSg3t1GRz2i3U-8kVSF
            // Use this line to send message without payload data
            // Message message = new Message.Builder().build();

            // use this line to send message with payload data
            Message message = new Message.Builder()
                    //.collapseKey("message")
                    //.timeToLive(241000)
                    .delayWhileIdle(true)
                    .addData("message", "Your message send")
                    .build();


                   /**/
            // Use this code to send to a single device
            // Result result = sender
            // .send(message,
            // "APA91bGiRaramjyohc2lKjAgFGpzBwtEmI8tJC30O89C2b3IjP1CuMeU1h9LMjKhmWuZwcXZjy1eqC4cE0tWBNt61Kx_SuMF6awzIt8WNq_4AfwflaVPHQ0wYHG_UX3snjp_U-5kJkmysdRlN6T8xChB1n3DtIq98w",
            // 1);

            // Use this for multicast messages
            MulticastResult result = sender.send(message, devicesList, 1);
            //sender.send(message, devicesList, 0);

            System.out.println(result.toString());
            if (result.getResults() != null) {
                int canonicalRegId = result.getCanonicalIds();
                if (canonicalRegId != 0) {
                }
            } else {
                int error = result.getFailure();
                System.out.println(error);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
于 2012-10-11T10:01:25.907 回答
5

com.google.android.gcm.server库已弃用。只需将您的消息编码为 JSON 对象并将其发布到 GCM URL https://android.googleapis.com/gcm/send

JSON 示例:

 {
   "registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...",...],
   "data" : {
     "Team" : "Portugal",
     "Score" : "3",
     "Player" : "Varela",
   },
 }

这里有更多http://developer.android.com/google/gcm/http.html

于 2013-12-16T21:22:03.573 回答
4

您可以在 Android SDK 目录中找到 gcm-client 和 gcm-server 的示例代码。这是开始的好点。目录是:

path_to_android_sdk/extras/google/gcm/samples

于 2012-10-12T07:12:43.880 回答
3
In your main function implement following code to send push notification to your app

final String apiKey = "specify your  api key generated by gcm";

To make http connection to gcm using following code

 URL url = new URL("https://android.googleapis.com/g...");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key="+apiKey);

        conn.setDoOutput(true);

JSON message format accepted by GCM

String input = "{\"registration_ids\" : [\"Specify token you got from GCM\"],\"data\" : {\"message\": \"hai  welcome\"},}";

To send notification

OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

In your client app you need to have proper BroadcastReceiver  class to receive the message sent from GCM
于 2015-10-01T16:14:49.060 回答
2

我会坚持让你测试开发者网站上提供的演示。我刚刚基于它创建了一个演示示例,其中包含执行演示示例应遵循的所有步骤。你可以查看我的博客,也可以从我的 github找到源代码。

于 2012-10-11T10:01:53.603 回答