How to send notification to Android app from Java server using GCM?

后端 未结 4 549
傲寒
傲寒 2020-12-08 02:43

I have my simple Android application which uses REST web service. Now I want to sent notification from my REST web service to Android application using GCM.

How do t

4条回答
  •  不知归路
    2020-12-08 03:23

    This is a function using to send notification from java to the app android. this code use JSONObject you must add this jar into project buildpath.

    note:I use 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();
    }
    }
    

    good luck

提交回复
热议问题