Friday, 11 November 2016

Notifications

Notifications are one of the ways the app can communicate information to the user. What makes notifications different is that they appear outside of the application UI.

In this simple example, we create a button which will send a notification to the user. Once the notification is clicked on, the device will go back to the main activity.

Let's take a quick look to the layout file first:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Notified!"
        android:id="@+id/notButton"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

This is the button I was talking about earlier.

The whole experiment is in a single class, our MainActivity:


 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
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        b = (Button)findViewById(R.id.notButton);

        b.setOnClickListener(this);
    }

    @SuppressLint("NewApi")
    void NotifyMe()
    {

        Intent intent = new Intent(this, MainActivity.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

        stackBuilder.addParentStack(MainActivity.class);

        stackBuilder.addNextIntent(intent);
        PendingIntent pIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

        Notification not = new Notification.Builder(this)
                .setContentTitle("This is the notification title")
                .setContentText("This is the content text")
                .setSmallIcon(R.drawable.icon)
                 .setContentIntent(pIntent)
                 .setAutoCancel(true).build();

        NotificationManager nm =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        nm.notify(0,not);

    }

    @Override
    public void onClick(View v) {

        if(v.getId() == R.id.notButton)
            NotifyMe();
    }
}

In the onCreate() I simply assign the Button reference and set its OnClickListener to the current class.

When the button is pressed, the method NotifyMe() is called.

In order to create a notification we use the Notification class and its Builder, in a similar way we create dialogs. While creating the notification we can assign other properties to it (line28 onwards), for example, a title, a message an icon, which will appear on the notification slider and a content intent. The latter is a pending intent called whenever the user clicks on the notification itself.

Observe where the title and text will appear in the notification slider:



The intent is created on line 19 and it is a standard way to spawn a new activity. In our case, the MainActivity. What happens after (line 21 - 26) is that we create an artificial stack for the activities we are launching  and we prevent the new activity to spawn on top of the other one. By doing so, once the user has pressed the notification and it's redirected to the main activity, if the back button is pressed, the application will shut down and the user will be sent to the home screen.

Finally, in order to execute the notification, we get the NotificationManager (line 35) and call the method notify(...). The parameters passed in this functions are: the notification id, which is used, for example, to cancel a notification through the notification manager, and the notification object itself, created previously.


Conclusion

Notifications are one of the most popular ways to notify the user. There are other things we can do to notifications, like apply expanded layouts or add inline reply actions, however, it is often enough to use simple notifications in order to communicate to the user, launching other activities to handle the following actions.

No comments:

Post a Comment