Android status bar notifications [complete tutorial with source code]

1 02 2014

Displaying status bar notification is a common way to unobtrusively inform user that something has happened (like new GMail message notification). In your app you can display it whenever you want. I will guide you how to do it from basics. This is how notifications are presented to the user:

Status bar notifications

Status bar notifications

Google’s documentation regarding the notifications is here.

Source Code

All the source code for this tutorial you can download here.

1. Create Basic notification

Notification consists of three obligatory parameters: title text, content text and small icon image. Here is the code that creates such notification:

private Notification createBasicNotification() {
	NotificationCompat.Builder builder = new Builder(getApplicationContext());
	Notification notification = builder
			.setSmallIcon(R.drawable.me)
			.setContentTitle(getString(R.string.notif_title))
			.setContentText(getString(R.string.notif_text))
			.build();

	return notification;
}

2. Display Basic Notification

After it is built, you can display it to the user with NotificationManager:

private void displayNotification(Notification notification) {
	NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
	notificationManager.notify(myNotificationId , notification);
}

Where myNotificationId is final int and is equal to 1:

private static final int myNotificationId = 1;

Thanks to this ID later you can refer to that notification and update its content  or hide it when you need it.

This is how the notification looks like right now:

notif_my_custom

3. Auto Hide notification after it is touched

As for now nothing happens when user touches notification. To make it disappear after touch add this clause to the builder:

setAutoCancel(true)

4. Start activity after notification is touched

The most common action after user selects notification is to open activity presenting the detailed data that caused notification to be issued. You have to assign PendingIntent to notification in order to do it:

private PendingIntent preparePendingIntent() {
	Intent intent = new Intent(getApplicationContext(), MainActivity.class);
	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

	PendingIntent pendingIntent = PendingIntent.getActivity(
			getApplicationContext(), 
			0, 
			intent, 
			PendingIntent.FLAG_UPDATE_CURRENT);
	return pendingIntent;
}

After that, you assign this intent to notification with the builder command:

.setContentIntent(notificationIntent)

Now you have a basic notification that can issue certain action. Further customization is optional and introduced in newer versions of Android. Since possibilities are quite big, it is worth to continue improving the notification.

5. Filling in remaining small notification fields

Here is the code to fill in the remaining fields of small notification (this should be called on bilder object):

.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.me))
.setContentInfo(getString(R.string.notif_contentInfo))
.setWhen(Calendar.getInstance().getTimeInMillis() + 1000*60+60)
.setVibrate(vibrationPattern)

In order to make vibrations work you need to define pattern (mine is quite sophisticated :P):

long[] vibrationPattern = {0, 200, 800, 200, 600, 200, 400, 200, 200, 200, 100, 200, 50, 200, 50, 200, 50, 200, 500, 200};

but it surely can be simplier:

// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 1000};

and require an VIBRATE permission in android manifest

<uses-permission android:name="android.permission.VIBRATE"/>

6. Apply big style to the notification

What actually is the Big Style? It is the notification with list of String. This is so called InboxStyle, since it is mainy used by GMail to notify user of incoming list of messages. This is how it looks like:

Notice that most of the elements are the same, except the 7 – the details list. Remember that big style works only for android versions higher than or equal to 4.2.

So now – how to build this list? Just create the notificationas it is done until now, and apply style to the builder:

.setStyle(inboxStyle)

And the inboxStyle is built like this:

private InboxStyle prepareBigNotificationDetails() {
	NotificationCompat.InboxStyle result = new InboxStyle();
	result.setBigContentTitle(getString(R.string.notif_inboxStyleTitle));
	result.addLine(getString(R.string.notif_inboxStyle_line1));
	result.addLine(getString(R.string.notif_inboxStyle_line2));
	result.addLine(getString(R.string.notif_inboxStyle_line3));
	result.addLine(getString(R.string.notif_inboxStyle_line4));
	result.addLine(getString(R.string.notif_inboxStyle_line5));
	result.addLine(getString(R.string.notif_inboxStyle_line6));
	return result;
}

Now test it (remember that only android 4.2 or higher will handle such notification). The result is like this:

InboxStyle notification

InboxStyle notification

notice that fields displayed on small notification are not visible in this style.

7. Updating notification content

Notification updates are quite simple: just set the fields you want to change with notification builder and call NotificationManagers’ notify() method providing the ID that you assigned to the notification that you need to update. The notification will be updated accordingly.

Download the Source Code

All the source code for this tutorial you can download here.

Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

Advertisements




iOS tutorial: progress indicator on status bar

5 01 2013

Here I will demonstrate how to show progress indicator on iPhone’s status bar. It is standard user interface element, so it is self explanatory to the user and extremely simple to develop.

Use it to indicate that some processing is taking place (for example network communication). This is how it is going to look like:

Status bar progress indicator

Status bar progress indicator

1. Show progress indicator

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

2. Hide progress indicator

[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!





Android push notifications with Google C2DM

19 05 2012

Push notification is message sent by server logic to specific android device. Message can be caught by specified application and handled in any way. For example some notification can be shown on the android status bar. Received message can also be handled by Application in the way which user will not even see. Application will just update its configuration, perform some action and close without showing anything on GUI.

Android users are familiar with it – GMail synchronization works this way. GMail server sends notification to the Android smartphone right after there is a new mail on the GMail Server. Developers can also make use from these notifications.

It is realized by permanently opened socket in the Android OS, listening for the messages sent from server. It is built-in component present in all Androids 2.2 and higher.

How to Do it?

The best description and instruction is on the google site. Key points are listed in this part. There are three components in the architecture:

1. Android Device

2. Google C2DM Server

3. Your application’s server with logic that decides when and to which device to send push message

How does it work?

1. Android device registers in C2DM Service, and receives its unique registration ID, sends this Id to App server where it is stored. Registration ID has to be periodically refreshed.

2. When application server logic decides to send push message it sends it to Google C2DM Server (using REST Webservice request) giving registration ID of target Android device

3. Google C2DM Server delivers message to Android device or queues it and retries if device is currently not available in network

4. C2DM message is converted by android OS to intent and Android application that is listening for message from app server receives it  by intentBroadcast and handles it.

What is required?

  • Need to have c2dm account (fast & free to create here). In basic contract you have 200 000 notifications per day for free(testing and low production apps). It can be extended.
  • User’s Google account set up on the android device and Google Play App installed
  • Additional Google account to create C2DM account and authorize while sending push from Application server
  • Android 2.2 or higher
  • Application permissions and listeners registrations defined in AndroidManifest.xml. Presented here.
 Features
  • you can pass parameters in push message (However remember that message size limit is 1024 bytes)
    • rather include parameters with instructions to download data, not the date itself due to message size limit
  • I don’t know if there is any QoS or guarantees regarding delay and reliability of this service. however due to my observations – mostly it works well. in most cases the message is delivered after few seconds after sending it.
Alternatives for using C2DM
Alternatives enables You to skip Google C2DM Server and service, and implement permanently listenting socket on the android device on You own. If you believe that it can be better than C2DM – you should read this article where alternative ways are described.

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!








%d bloggers like this: