如何使用GCM从Java服务器向Android应用程序发送通知?

时间:2013-04-02 07:22:44

标签: java android web-services google-cloud-messaging

我有一个使用REST Web服务的简单Android应用程序。现在我想使用GCM从我的REST Web服务向Android应用程序发送通知。

这是怎么回事?这个要求有没有简单的教程?我搜索并找到了Google API,但我不明白。

4 个答案:

答案 0 :(得分:5)

我为GCMUtils项目创建了一个基于Java的测试服务器,实现为maven插件: https://code.google.com/p/gcmutils/wiki/MavenPlugin#Test_server

以下是源代码:https://github.com/jarlehansen/gcmutils/tree/master/gcm-test-server

maven插件的来源:https://github.com/jarlehansen/gcmutils/tree/master/gcmutils-maven-plugin

也许这可以帮助您入门?

答案 1 :(得分:1)

这是一个用于从java向app android发送通知的函数。此代码使用JSONObject,您必须将此jar添加到项目构建路径中。

注意:我使用fcm

 import java.io.OutputStreamWriter;
 import java.net.HttpURLConnection;
 import java.net.URL;

import org.json.JSONObject;

public class FcmNotif {
  public final static String AUTH_KEY_FCM ="AIzB***********RFA";
  public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";

// userDeviceIdKey is the device id you will query from your database

public void pushFCMNotification(String userDeviceIdKey, String title, String message) throws Exception{

String authKey = AUTH_KEY_FCM;   // You FCM AUTH key
String FMCurl = API_URL_FCM;     

URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);

conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");

JSONObject json = new JSONObject();
json.put("to",userDeviceIdKey.trim());
JSONObject info = new JSONObject();
info.put("title", title); // Notification title
info.put("body", message); // Notification body
info.put("image", "https://lh6.googleusercontent.com/-sYITU_cFMVg/AAAAAAAAAAI/AAAAAAAAABM/JmQNdKRPSBg/photo.jpg");
info.put("type", "message");
json.put("data", info);
System.out.println(json.toString());

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();
}
}
祝你好运

答案 2 :(得分:0)

  

关注此网址   https://firebase.google.com/docs/cloud-messaging/send-message

FCM网址

private String ANDROID_NOTIFICATION_URL = "https://fcm.googleapis.com/fcm/send"

通知密钥

private String ANDROID_NOTIFICATION_KEY = "Your key";

Java代码

private void sendAndroidNotification(String deviceToken,String message,String title) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject obj = new JSONObject();
        JSONObject msgObject = new JSONObject();
        msgObject.put("body", message);
        msgObject.put("title", title);
        msgObject.put("icon", ANDROID_NOTIFICATION_ICON);
        msgObject.put("color", ANDROID_NOTIFICATION_COLOR);

        obj.put("to", deviceToken);
        obj.put("notification",msgObject);

        RequestBody body = RequestBody.create(mediaType, obj.toString());
        Request request = new Request.Builder().url(ANDROID_NOTIFICATION_URL).post(body)
                .addHeader("content-type", CONTENT_TYPE)
                .addHeader("authorization", "key="+ANDROID_NOTIFICATION_KEY).build();

        Response response = client.newCall(request).execute();
        logger.debug("Notification response >>>" +response.body().string());
    }

就是这样!!!

答案 3 :(得分:0)

  1. package com.test;

    import java.io.BufferedReader; import java.io.IOException;进口 java.io.InputStreamReader中; import java.io.OutputStream;进口 java.net.HttpURLConnection中; import java.net.URL;

    公共类Firebase {

    public static void main(String[] args) throws IOException {         final
    

    String apiKey = “AAAAqf1B9uQ:********** _ 1MoeQBVPbVROXuyD4ERyV-i6nva0LAic9uRotN80C9utoaGL9Sp1GjrPr5-mtJBlxVNbuqG1zeg9LBnslZw-vyud3jW-11SWDfLBB26bcHuAi8bdnQCPcj3DWKX2h”;         网址url =新网址(“https://fcm.googleapis.com/fcm/send”);         HttpURLConnection conn =(HttpURLConnection)url.openConnection();         System.setProperty( “javax.net.debug”, “全”);         conn.setDoOutput(真); conn.setRequestMethod( “POST”);         conn.setRequestProperty(“Content-Type”,“application / json”);         conn.setRequestProperty(“授权”,“key =”+ apiKey);

        conn.setDoOutput(true);
    
        String input = "{\r\n\"to\":
    

    \ “fdaxKOmRcAI:APA91bEXILacYEjypsbusKXHV_TuEzt_vsqhI5OxH - ****************** - l2qGIORSiE0W5B2d74yjXAz60l \”, \ r \ n \“通知\”:{\ r \ n \“title \”:\“title \”,\ r \ n \“body \”:\“ 单个vijay的主体\“\ r \ n} \ r \ n}”;

                OutputStream os = conn.getOutputStream();       os.write(input.getBytes());         os.flush();         os.close();
    
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + input);
        System.out.println("Response Code : " + responseCode);
    
        BufferedReader in = new BufferedReader(new
    

    的InputStreamReader(conn.getInputStream())); String inputLine;         StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);         }       in.close();
    
        // print result         System.out.println(response.toString());
    
    }
    

    }

    1. 列表项