Click here to Skip to main content
15,867,308 members
Articles / Internet of Things / Wearables
Article

Android Wear Notification

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
16 Oct 2015CPOL4 min read 25.6K   178   1   4
Let us discuss about Android Wear Notification and learn with example on how to build and show notifications on wearables

Introduction

In this article, I will discussing with you how to build Notifications in Android Wear. Notifications are generally common in most of the wearable applications. As a developer, one has to understand how to build notifications.

The following combination of classes are used for building notifications

  1. Notification
  2. NotificationCompact.Action
  3. NotificationCompat.Builder
  4. NotificationCompat.WearableExtender
  5. NotificationManagerCompat

If you are an Android programmer, you should be already knowing how to create notifications and use them in your application.

The notifications in wearables are designed in a similar fashion but there is something called stacked notification that you see only on wearables. Stacked notifications are nothing but a group of notifications which are stacked together and is shown as a single card. It lets the user to choose and read all notifications.

Following are the links to various examples with which you can learn how the Notification is built.

Background

Please take a look into the below link to have some understanding about Android Wear.

http://www.codeproject.com/Articles/1038337/Introduction-to-Android-Wear

Using the code

Example 1 – Constructing a Notification instance

Below is the code sample for constructing a simple Notification instance. We are yet to display the notification which you will learning next.

Notification notification = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle("CP notification")
        .setContentText("CodeProject wear notification!")
        .build();

Example 2 – Extending Notification

In this example, we will be adding a wearable feature to notification by extending the notification instance to have WearableExtender instance.

You may set any of the available properties of WearableExtender as you wish. Finally it has to be attached to the Notification instance by making a call to the “extend” method and passing in the WearableExtender instance. Also in this example, you can see below a NotificationManagerCompat instance is being used to create a wearable notification.

Quote: Code Info

Please note – The below code snippet is part of open source sample - https://github.com/LarkspurCA/WearableSuggest

NotificationCompat.WearableExtender wearableExtender =
        new NotificationCompat.WearableExtender()
                .setHintShowBackgroundOnly(true);

Notification notification =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("Hello Android Wear")
                .setContentText("First Wearable notification.")
                .extend(wearableExtender)
                .build();

NotificationManagerCompat notificationManager =
        NotificationManagerCompat.from(this);

int notificationId = 1;

notificationManager.notify(notificationId, notification);

Image 1

Example 3 – Stacked Notification

In this example, we will see how to build a stacked notification. Below is the code snippet, shows how to display a stacked notifications.

You can see below, you can have two or more Notification instances and a NotificationManagerCompat instance is used for displaying grouped notifications. In order for the stacked notifications to be shown together, we have to group the Notification and that’s done by setting the same group key to all the Notification instance which you are interested in.

public void DisplayStackedNotifications() {

    final String GROUP_KEY = "group_messages";

    Notification notification1 = new NotificationCompat.Builder(this)
            .setContentTitle("Message from User1")
            .setContentText("What's for lunch? "
                    + "Can we have a veggie burger?")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setGroup(GROUP_KEY)
            .build();

    Notification notification2 = new NotificationCompat.Builder(this)
            .setContentTitle("Message from CodeProject")
            .setContentText("How is your article writing going?")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setGroup(GROUP_KEY)
            .build();

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

    notificationManager.notify(1, notification1);
    notificationManager.notify(2, notification2);
}

Image 2

Example 4 – Adding action(s) to notification

In this example, let us see how we can add actions to notifications. There are times, you wish to not only show notifications but if you are also interested in including some of the actions that should be triggered, say you wish to open a new activity or do some other interesting things, then you should be adding actions. 

There is something called primary actions on wearables, you can set a content action on NotificationCompat.Builder by making a call to setContentIntent.

Quote: Code Info

Please Note – The below code snippet is based on http://stackoverflow.com/questions/6391870/how-exactly-to-use-notification-builder

public void NotificationWithPrimaryIntent()
{
    int notificationID = 0;
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Notification")
                    .setContentText("Test notification with Content Intent");

    Intent notificationIntent = new Intent(this, MyDisplayActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);

    NotificationManager notificationManager = 
               (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificationID, builder.build());
}

Image 3 Image 4

Let us see how to add custom action to notification. Below is the code snippet for the same. Here’s what we do.

1)    We are creating an Intent instance with an action ACTION_DIAL to dial the wearable connected phone. 

2)    A PendingIntent instance is created to use the call phone Intent. Next, we are building a NotificationCompat.Action with an icon, text and the pending intent. 

3)    NotificationCompat.Builder instance is created with an icon, text, title. Also you will notice, there is an action being added by making a call to addAction passing in the NotificationCompat.Action instance.

4)    At last, a NotificationManager instance is created to notify the user by making a call to “notify” method with the notification id and NotificationCompat.Builder instance. 

public void NotificationWithAction()
{
    int notificationID = 0;
    Intent callPhoneIntent = new Intent(Intent.ACTION_DIAL);

    PendingIntent callPhonePendingIntent = PendingIntent.getActivity(this, 0,
            callPhoneIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Action callPhoneAction =
            new NotificationCompat.Action.Builder(R.mipmap.ic_launcher, "Call Phone",
                                                  callPhonePendingIntent)
            .build();

    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Notification")
                    .setContentText("Call Phone")
                    .addAction(callPhoneAction);

    NotificationManager notificationManager = 
                 (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificationID, builder.build());
}

Image 5 Image 6

Example 5 – Notification through broadcast receiver 

In this example, we will try to understand how to display notification within the broadcast receiver. We need an Intent instance to trigger or send a broadcast. Also the BroadcastReceiver is responsible for receiving the broadcast message. 

We will be modifying the AndroidManifest.xml file to include the broadcast receiver with an intent filter action as com.example.ranjan.wearablenotification.SHOW_NOTIFICATION. It’s very important to add this change else the broadcast receiver won’t be able to receive anything.

<receiver
    android:name=".MyPostNotificationReceiver"
    android:exported="true" >
    <intent-filter>
        <action android:name="com.example.ranjan.wearablenotification.SHOW_NOTIFICATION" />
    </intent-filter>
</receiver>

Below is the code snippet of the broadcast receiver. We are overriding the onReceive method and implementing the code for notification. You can notice below a Notification Instance is created with an icon, title etc. Then we use a NotificationManager instance to notify the same.

public class MyPostNotificationReceiver extends BroadcastReceiver {
    public static final String CONTENT_KEY = "contentText";

    public MyPostNotificationReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent displayIntent = new Intent(context, MyDisplayActivity.class);
        String text = intent.getStringExtra(CONTENT_KEY);

        Notification notification = new Notification.Builder(context)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(text)
                .extend(new Notification.WearableExtender()
                        .setDisplayIntent(PendingIntent.getActivity(context, 0, displayIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT)))
                .build();

        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
              .notify(0, notification);

        Toast.makeText(context, context.getString(R.string.notification_posted),
                      Toast.LENGTH_SHORT).show();
    }
}

Below is the code snippet for sending broadcast message. We are creating an Intent instance and set an action same as we set with in the intent-filter. The notification text is set by making a call to putExtra with a key as CONTENT_KEY and value from R.string.title

public class MyStubBroadcastActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent();
        intent.setAction("com.example.ranjan.wearablenotification.SHOW_NOTIFICATION");
        intent.putExtra(MyPostNotificationReceiver.CONTENT_KEY, getString(R.string.title));
        sendBroadcast(intent);
        finish();
    }
}

Points of Interest

There's always something new I'm learning. Notifications are given high importance in Android Wear and it's important to learn and use it to the best.

History

Version 1.0 - Published initial version of the article with a code sample - 10/16/2015

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Profile

Around 10 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.

In Brief

Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.

Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF

Software Development

Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI

Healthcare Domain Experience

CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability

Education

B.E (Computer Science)

CodeProject Contest So Far:

1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro

2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics

3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin

4. Intel App Innovation Contest 2013 - eHealthCare

5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Contest 2014

6. Grand Prize Winner of CodeProject Android Article Contest 2014

7. Grand Prize Winner of IOT on Azure Contest 2015

Comments and Discussions

 
QuestionContact details Pin
Justinru12-Jan-16 13:45
Justinru12-Jan-16 13:45 
QuestionGood Article Pin
Santhakumar M17-Nov-15 8:03
professionalSanthakumar M17-Nov-15 8:03 
AnswerRe: Good Article Pin
Ranjan.D17-Nov-15 13:54
professionalRanjan.D17-Nov-15 13:54 
GeneralRe: Good Article Pin
Santhakumar M17-Nov-15 20:41
professionalSanthakumar M17-Nov-15 20:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.