Android Basic Training Course: Alerting users by Notifications System

    A notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.
    Notifications, as an important part of the Android user interface, have their own design guidelines. Big style notification was introduced on Android version 4.1.x. If you are building app that supports older android phones like android 2.3 or above, in such cases you may like to go for  NotificationCompat.Builder for showing notifications.

Creating a Notification and set properties

    By using a Notification Builder instance, you can easily create a Notification object though this simple code:
Notification notification = new NotificationCompat.Builder(this)
    A Notification has some necessary attributes which you must declared like:
  • A small icon: set by setSmallIcon()
  • A title, set by setContentTitle()
  • Detail text, set by setContentText()
    And this is full code for this creating Notification process though  NotificationCompat.Builder:
Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_notify) // icon of notification
                .setContentTitle(notificationTitle) // title of the notification
                .setContentText(notificationMessage) // content of the notification
                .setContentIntent(pi) // content Intent
                .setAutoCancel(true) // auto dismiss notification when user clicked
                .build();

Attach action with Intent

    This is an optional part and required if you want to attach an action with the notification. An action allows users to go directly from the notification to an destination (received)  Activity  in your application, where they can look at one or more events or do further work.
    The action is defined by a  PendingIntent  containing an  Intent  that starts an  Activity  in your application:
        Intent intent = new Intent(this, ReceiveNotifyActivity.class);
        intent.putExtra("Title", notificationTitle);
        intent.putExtra("Body", notificationMessage);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    In this example, I use putExtra() method of Intent to put data (notification title and body message) to the receiving Activity and show these details here.

Invoking the Notification

    Finally, you pass the Notification object to the system by calling NotificationManager.notify()  to send your notification:
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); //initializing a NotificationManager object
notificationManager.notify(0, notification);
    Over here, adding some code, we have full code for "pushing notification" Activity:
package devexchanges.info.notificationsample;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class CreateNotifyActivity extends AppCompatActivity {

    private View btnCreateNotify;
    private EditText txtTitle;
    private EditText txtMsg;

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

        txtMsg = (EditText)findViewById(R.id.msg);
        txtTitle = (EditText)findViewById(R.id.title);

        btnCreateNotify = findViewById(R.id.btn_create);
        btnCreateNotify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                createNotification(txtTitle.getText().toString(), txtMsg.getText().toString());
                finish(); // In this example, I finish current activity after push a notify
            }
        });

    }

    private void createNotification(String notificationTitle, String notificationMessage) {
        Intent intent = new Intent(this, ReceiveNotifyActivity.class);
        intent.putExtra("Title", notificationTitle);
        intent.putExtra("Body", notificationMessage);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_notify) // icon of notification
                .setContentTitle(notificationTitle) // title of the notification
                .setContentText(notificationMessage) // content of the notification
                .setContentIntent(pi) // content Intent
                .setAutoCancel(true) // auto dismiss notification when user clicked
                .build();

        //Building notification
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);
    }
}
    Provide a layout for it by a xml file:
    This screen after running and typing some texts to EditTexts :

Making a destination Activity

   Like all of Android apps, you always must have a receiving notification Activity which appear when user click at each Notification object. With the above code, I put the Notification title and message to the destination Activity, so you get them through Intent, source code for it is so simple:
package devexchanges.info.notificationsample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class ReceiveNotifyActivity extends AppCompatActivity {

    private TextView notificationTitle;
    private TextView notificationMessage;

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

        notificationMessage = (TextView) findViewById(R.id.msg);
        notificationTitle = (TextView) findViewById(R.id.title);

        Bundle extras = getIntent().getExtras();

        notificationMessage.setText("Notification content: " + extras.getString("Body"));
        notificationTitle.setText("Notification title: " + extras.getString("Title"));
    }
}
    And this is it's layout (xml file):
    Running program, after hit "create Notification" button at the first screen, you will have a notification appear at notification area:
    Clicking at it, your app will open the receiving notification Activity and show it's details:

Conclusions

    Through this post, I provided a simple project to create and showing the notification. Further, you can find out your shelf the way to create it with sound and some advanced options (for example: create notification with multiline). The notification system is very flexible, but also easy when you just need a simple notification displayed. Your users will benefit from notifications by seeing what is going on in the background and being reminded about the application.




Share


Previous post
« Prev Post
Next post
Next Post »