Android push notification is a service which notifies you that has any new data come or not in your smart device.
Android push notification is a service used by developers to send data to Android smartphones.
There are several different methods that can be used to implement Android push messages, the standard way is GCM (Google Cloud Messaging) but the alternatives are everywhere.
So here, We are using simply an alarmManager to make a request to the server after an interval and our custom API to make a response to android smartphones.
1. Make your pendingIntent and set alarm
This is your primary activity named MainActivity.java, Here we have to set pendingIntent where pendingIntent is the instance of the Intent that starts the Activity when a user touches the push notification.
1 2 3 4 5 |
Intent alarmIntent = new Intent(this, AlarmReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); int interval = 1000 * 60 * 60 * 2; alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent); |
In above block of code,
alarmIntent – is an object of Intent.
PendingIntent – is the instance of the Intent that starts the Activity when a user touches the push notification.
AlarmManager – This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future.
PendingIntent.FLAG_UPDATE_CURRENT – Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent. For use with getActivity, getBroadcast, and getService.
1 |
int interval = 1000 * 60 * 60 * 2; |
Here we have set the interval of 1000 * 60 * 60 * 2. Means It will run after every 2 hr.
2. Make your BroadcastReceiver class
In step 2, We are making a BroadcastReceiver class named AlarmReceiver.java.
Here, we send a request to the server and server send a response to the client (mobile device) and show to the form of push notification on smartphones.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
package webkul.xyz.abc; import org.json.JSONObject; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.support.v4.app.NotificationCompat; import android.text.Html; import android.util.Log; public class AlarmReceiver extends BroadcastReceiver { static Context thisContext; Object response = null, mainResponse = null; JSONObject mainObject; @Override public void onReceive(Context context, Intent intent) { thisContext = context; new Connection().execute(context); } private class Connection extends AsyncTask < Context, String, Object > { private Editor editor; @Override protected String doInBackground(Context...arguments) { try { // getNotifications is API which will give the notification data SoapObject mainRequest = new SoapObject(NAMESPACE, "getNotifications"); SoapSerializationEnvelope requestEnvelop = getSoapSerializationEnvelope(mainRequest); HttpTransportSE ht = getHttpTransportSE(); ht.call(NAMESPACE, requestEnvelop); // some connection code which send the request to the server and get response mainResponse = (Object) requestEnvelop.getResponse(); String mainResponseAsString = mainResponse.toString(); mainObject = new JSONObject(mainResponseAsString); } catch (Exception e) { Log.d("Exception", e.toString()); return "no"; } } @Override protected void onPostExecute(Object result) { Intent intent = new Intent(thisContext, category.class); // this is the response which is show on the push notification. String notificationMessage = mainObject.getString("content"); String notificationSubTitle = mainObject.getString("subTitle"); String notificationTitle = mainObject.getString("title"); notification(intent, notificationSubTitle, notificationTitle, i); } void notification(Intent intent, String notificationMessage, String notificationTitle, int id) { PendingIntent pIntent = PendingIntent.getActivity(thisContext, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(thisContext).setSmallIcon(R.drawable.ic_notification) .setTicker(notificationMessage) .setContentTitle(notificationTitle) .setContentText((Html.fromHtml(notificationMessage))) .setContentIntent(pIntent); Notification notification = builder.build(); // default phone settings for notifications notification.defaults |= Notification.DEFAULT_VIBRATE; notification.defaults |= Notification.DEFAULT_SOUND; // cancel notification after click notification.flags |= Notification.FLAG_AUTO_CANCEL; // show scrolling text on status bar when notification arrives notification.tickerText = notificationTitle; notification.icon = R.drawable.ic_notification; // notifiy the notification using NotificationManager NotificationManager notificationmanager = (NotificationManager) thisContext.getSystemService(Context.NOTIFICATION_SERVICE); // this is the method which finally notifies the message on the smart mobile phones notificationmanager.notify(id, notification); } private final SoapSerializationEnvelope getSoapSerializationEnvelope(SoapObject request) { SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = false; envelope.xsd = SoapSerializationEnvelope.XSD; envelope.enc = SoapSerializationEnvelope.ENC; envelope.setOutputSoapObject(request); return envelope; } private final HttpTransportSE getHttpTransportSE() { HttpTransportSE ht = new HttpTransportSE("URL", 60000); ht.debug = true; ht.setXmlVersionTag("<!--?xml version=\"1.0\" encoding= \"UTF-8\" ?-->"); return ht; } } } |
In above code,
BroadcastReceiver – broadcast receiver who will intercept communication and notify us that something is working in our mobile. It is of 2 types:
- Normal broadcasts (sent with
Context.sendBroadcast
) are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time. This is more efficient, but means that receivers cannot use the result or abort APIs included here. - Ordered broadcasts (sent with
Context.sendOrderedBroadcast
) are delivered to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won’t be passed to other receivers. The order receivers run in can be controlled with theandroid:priority
attribute of the matching intent-filter; receivers with the same priority will be run in an arbitrary order.
NotificationCompat.Builder – Builder class for NotificationCompat
objects. Allows easier control over all the flags, as well as help constructing the typical notification layouts.
3. Register your broadcast receiver class in AndroidManifest.xml
An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest.xml file.
1 2 3 4 5 |
<receiver android:name="com.webkul.mobikul.AlarmReceiver" android:enabled="true" android:exported="true" > </receiver> |
Paste this xml code inside your <application> tag.