You can use MQTT to create a push notification service. (Note: apps like Facebook use MQTT for push notifications.)
So, to create a push notification service, you need a MQTT broker running on a server (I recommend MQTT Mosquitto and a bachground service running on an Android device.
Code for the MQTT service (can be used both on the server and on the client sode):
/** * MQTTManager class provide methods to connect, subscribe, publish, and listen to MQTT broker */ public class MQTTManager { private final String TAG = "MQTT"; private final String BROKER_URL = "http://mqtt-dashboard.com/info/broker:1883"; //change it to your broker URL private MqttClient mqttClient; private String CLIENT_ID = "123" private String topic = "ABC" private int keepAliveInterval=60*5; private MqttConnectOptions opt; /** * Constructor * @throws MqttException */ protected MQTTManager() throws MqttException { opt=new MqttConnectOptions(); opt.setKeepAliveInterval(keepAliveInterval); opt.setConnectionTimeout(10); mqttClient = new MqttClient(BROKER_URL, CLIENT_ID, new MemoryPersistence()); mqttClient.setCallback(new MQTTCallback(BROKER_URL, CLIENT_ID, topic)); } /** * Connects to the MQTT broker service on server side. */ public void connect(){ try { mqttClient.connect(opt); } catch (MqttException e) { Log.e(TAG, "Error while connecting to mqtt broker: "+e.toString()); } } /** * Subscribes the device to the topic provided via constructor */ public void subscribeDevice(){ try { mqttClient.subscribe(this.topic); } catch (MqttException e) { Log.e(TAG, "Error while subscribing to mqtt broker: "+e.toString()); } } /** * Publishes the message to the MQTT broker service. * @param String Message that needs to be published */ public void publishToDevice(String message){ try { MqttTopic mtopic=mqttClient.getTopic(this.topic); MqttMessage msg= new MqttMessage(message.getBytes()); mtopic.publish(msg); } catch (MqttException e) { Log.e(TAG, "Error while publishing to mqtt broker: "+e.toString()); } } /** * Inner class for mqtt callback */ public class MQTTCallback implements MqttCallback{ final private String TAG = "MQTT"; private String BROKER_URL; private String CLIENT_ID; private String TOPIC; private MqttClient mqttClient; public MQTTCallback(String BROKER_URL, String CLIENT_ID, String TOPIC) { this.BROKER_URL= BROKER_URL; this.CLIENT_ID = CLIENT_ID; this.TOPIC=TOPIC; } public void connectionLost(Throwable arg0) { connect(); } public void deliveryComplete(MqttDeliveryToken arg0) { if(arg0==null) System.out.print("Message delivered"); } public void messageArrived(MqttTopic arg0, MqttMessage arg1) throws Exception { // MESSAGE ARRIVES HERE!! argo-> device id & arg1 --> message } } }
To find out more, you can check the MQTT push notification service implemented in this project: SenSocial , which I implemented.
If you do not have a broker running on your server, you can try the publicly available broker MQTT Mosquitto: MQTT BROKER
source share