使用 Google GCM 发送推送通知

Sending push notification using Google GCM

我一直在关注 Set Up a GCM Client App tutorial 并试图了解他们提供的演示应用程序,但我无法理解如何使用此服务发送推送通知。

以上指南将我带到一个 "Generating InstanceID token" 屏幕,其中包含永无止境的 ProgressBar。本程序源码可在此处获取:https://github.com/googlesamples/google-services/tree/master/android/gcm/app/src/main

使用上面的源代码后,我在简单下游消息传递旁边尝试了这个:https://developers.google.com/cloud-messaging/downstream 以便向应用程序用户发送推送。

我不明白应该如何使用它向我的应用用户发送通知。

我有一个服务器,我很擅长 PHP,要使用 GCM 向我的应用程序用户发送推送通知还需要做什么?

终于设法将消息发送到 TextView! 怎么变成推送?

public class GcmService extends GcmListenerService {

    @Override
    public void onMessageReceived(String from, Bundle data) {
        JSONObject jsonObject = new JSONObject();
        Set<String> keys = data.keySet();
        for (String key : keys) {
            try {
                jsonObject.put(key, data.get(key));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        try {
            sendNotification("Received: " + jsonObject.toString(5));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDeletedMessages() {
        sendNotification("Deleted messages on server");
    }

    @Override
    public void onMessageSent(String msgId) {
        sendNotification("Upstream message sent. Id=" + msgId);
    }

    @Override
    public void onSendError(String msgId, String error) {
        sendNotification("Upstream message send error. Id=" + msgId + ", error" + error);
    }

    private void sendNotification(final String msg) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (MainActivity.mTextView != null) {
                    MainActivity.mTextView.setText(msg);
                }
            }
        });
    }
}

假设您在 Google Developers Console 创建了一个新项目并记下了 2 个值:项目编号,将在客户项目中用作 SENDER_ID;和 API 服务器密钥(在 Credentials 创建),它将在服务器项目中用作 API_KEY。

您可以通过我在以下问题中的回答找到更多关于基本服务器项目的信息。在第二个link中,你会在Java中找到一个服务器项目的示例代码,然后你可以参考它的逻辑在你的PHP项目中实现:

希望对您有所帮助!