Send push notifications to Android

走远了吗. 提交于 2019-12-01 05:43:27

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 :)

If you want to send Push Notification on multiple platform use Parse.com but problem here is Parse.com is going to stop its services in January 28, 2017. You have alternatives like urban airship and many more. I personally suggest urban airship.

You can try Sever Sent Event(SSE) from Jersey to see if that meets your requirement.

You can use Google Cloud Messaging to do this, it now supports Android and iOS. Its free and has no limits to number of notification.

How it works?

Simply, you need to generate Registration ID from your mobile and send it to your server, then when you need to send a notification just send the registration ID and the message to GCM.

Please check this link from Google about GCM:

https://developers.google.com/cloud-messaging/

and this link just take a quick look about server code (written in PHP):

http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

there is some changes you can notice it in first link.

Finally, check this link it explains the client code step by step:

http://www.androidwarriors.com/2015/10/push-notification-using-gcm-in-android.html

I hope this helps you, do not hesitate to ask any question.

Send push notifications to Android

 private void pushNotification(String handlename) {
        StringEntity entity = null;
        JSONObject jsonObject = new JSONObject();
        String referesedtoken = FirebaseInstanceId.getInstance().getToken();
        try {
            jsonObject.put("to", clientToken);
            jsonObject.put("priority", "high");
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(referesedtoken);
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("body", handlename);
            jsonObject1.put("commonContact", commonContact);
            jsonObject1.put("profileType", profileType);
            jsonObject1.put("notification-type", "chat");
            jsonObject1.put("target", handlename);
            jsonObject1.put("email", authPreferences.getEmailAddress());
            jsonObject1.put("UniqueId", authPreferences.getUserUid());
            jsonObject1.put("profilePicUrl", authPreferences.getMyProfilePicImageUrl());
            jsonObject1.put("title", profileBeenClasss.getFirstname() + " " + profileBeenClasss.getLastname() + " has sent message to you");
            jsonObject.put("registrationIDs", jsonArray);
            jsonObject.put("notification", jsonObject1);
            entity = new StringEntity(jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
        client.setTimeout(80000);
        client.addHeader("Authorization", "key=AIzaSyCxKiM-LlNHfUOZ3QiiZfSGTo3vTAZdAAI");
        client.post(this, "https://fcm.googleapis.com/fcm/send", entity, "application/json", new TextHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, String res) {
                        System.out.println("Send Notification sucessfully" + res.toString());
                   }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
                        System.out.println("notification fail", res.toString());
                    }

                }
        );

    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!