Send push notifications to Android

前端 未结 5 656
长情又很酷
长情又很酷 2021-01-13 00:17

I am currently developing Java web services that run on WebLogic on a server. These web services are called by a mobile application, which is developed by another team. Ther

5条回答
  •  余生分开走
    2021-01-13 00:37

    Prerequisite for GCM Application

    1. Google API Server Key
    2. GCM RegId of the Android Device to communicate via GCM

    If you get clear concept about GCM, please visit here

    Your hosted server need not need any Ip/HostName to send Message cause this message will deliberate via com.google.android.gcm.server.Sender this class. This class will internally communicate to GCM Server. You are configuring this class using this way:

    Sender sender = new Sender(API_KEY);
    

    You can send message using GCM server. This code will work for sending push notification to devices. This can send notification to any Android/IOS apps from java server.

    Here is the jar of this GCM server library.

    Here, this constructor get MESSAGE and deviceGcmId where have to send Push Message.

    public PushNotification(String id, String message) {
                this.receiverID = id;
                this.gcmMessage = message;
            }
    

    Here is sample code:

    import com.google.android.gcm.server.Message;
    import com.google.android.gcm.server.MulticastResult;
    import com.google.android.gcm.server.Result;
    import com.google.android.gcm.server.Sender;
    
    public class PushNotification {
        private String receiverID;
        private String gcmMessage;
        String MESSAGE_KEY = "YOUR_MESSAGE_KEY";
        String API_KEY = "YOUR_API_KEY";
    
        Result result;
        Sender sender;
        Message message;
        MulticastResult multicastResult;
    
        public PushNotification() {
        }
    
        public PushNotification(String id, String message) {
            this.receiverID = id;
            this.gcmMessage = message;
        }
    
        public boolean sendSinglePushNotification() {
            try {
                sender = new Sender(API_KEY);
                message = new Message.Builder().timeToLive(30).addData(MESSAGE_KEY, gcmMessage).build();
                result = sender.send(message, receiverID, 1);
                if (result != null && result.getErrorCodeName() == null) {
                    return true;
                }
            } catch (Exception ex) {
                System.err.println(ex.getMessage());
            }
            return false;
        }
    }
    

    You can call this class using this way:

    PushNotification notification=new PushNotification("DEVICE_GCM_ID","MESSAGE HAVE To SEND");    
    notification.sendSinglePushNotification();
    

    That's it :)

提交回复
热议问题