web-dev-qa-db-fra.com

Comment envoyer une notification à une application Android depuis un serveur Java à l'aide de GCM?

J'ai une application Android simple qui utilise le service Web REST. Maintenant, je souhaite envoyer une notification de mon service Web REST à une application Android à l'aide de GCM.

Comment ça? Existe-t-il un tutoriel simple pour cette exigence? J'ai cherché et trouvé Google API, mais je ne le comprends pas. 

21
Bhushan

J'ai créé un serveur de test basé sur Java, implémenté en tant que plug-in maven, pour le projet GCMUtils: https://code.google.com/p/gcmutils/wiki/MavenPlugin#Test_server }

Voici le code source: https://github.com/jarlehansen/gcmutils/tree/master/gcm-test-server }

Source pour le plugin maven: https://github.com/jarlehansen/gcmutils/tree/master/gcmutils-maven-plugin }

Peut-être que cela peut vous aider à démarrer?

5
Jarle Hansen

Cette fonction permet d’envoyer des notifications de Java à l’application Android. ce code utilise JSONObject, vous devez ajouter ce fichier jar dans le chemin de construction du projet.

note: j'utilise 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();
}
}

bonne chance

1
Mohamed
  1. package com.test;

    importer Java.io.BufferedReader; importer Java.io.IOException; importer Java.io.InputStreamReader; importer Java.io.OutputStream; importer Java.net.HttpURLConnection; importer Java.net.URL;

    classe publique Firebase {

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

    Chaîne de vœux URL url = nouvelle URL (" https://fcm.googleapis.com/fcm/send "); HttpURLConnection conn = (HttpURLConnection) url.openConnection (); System.setProperty ("javax.net.debug", "tous"); conn.setDoOutput (true); conn.setRequestMethod ("POST"); conn.setRequestProperty ("Content-Type", "application/json"); conn.setRequestProperty ("Authorization", "key =" + apiKey);

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

    \ "fdaxKOmRcAI: APA91bEXILacYEjypsbusKXHV_TuEzt_vsqhI5OxH - ************** - l2qGIORSiE0W5B2d74yjXAz60l \", \\.\": \" title\",\r\n \" body\": \" Corps d'un seul 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. Élément de liste
0
Vijay Bharti

Suivez cette URL https://firebase.google.com/docs/cloud-messaging/send-message

FCM URL

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

Clé de notification

private String Android_NOTIFICATION_KEY = "Your key";

Code 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());
    }

C'est tout !!!

0
Parth Solanki