Android Notification

1, What is a notification?

2, How to Create a notification object?

3, What would happen once a user touched the notification?

———————————————————————

1 What is a notification?

A notification is a message sent from an APP and will display an icon in the phone’s notification area.

2 How to create a notification Object?

There are mainly two classes involves to create a notification object, first is NotificationCompat.Build which is specifify the UI information and actions for the notification, like the title, the content, the ringtone, the vibration, etc. And then we use NofiticationManager.nofify to launch the notification.

protected void onCreate(Bundle savedInstanceState) {
        ...
        notification = new NotificationCompat.Builder(this);
        notification.setAutoCancel(true);
    }

public void sendNotification(View view) {
        // Build the notification
        notification.setSmallIcon(R.mipmap.ic_launcher);
        notification.setTicker("This is the Ticker");
        notification.setWhen(System.currentTimeMillis());
        notification.setContentTitle("Here is the Title");
        notification.setContentText("This is the body of the content");
        // set sound for the notification
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        // Set Custom Sound:
        Uri customSound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.here);
        notification.setSound(customSound);   // default or custom sound
        // set vibrate
        long[] vibrate = {500,500, 100, 200, 300};
        notification.setVibrate(vibrate);

        // set notification action: allow user to go from the notification to an Activity
        Intent i = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setContentIntent(pendingIntent);

        // Builds notification and issue it
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        nm.notify(uniqueID,notification.build());
    }

 

3, What would happen once a user touched the notification?

We should build an PendingIntent object (viewed the attached code), which defines the action when the user touched interact with the notification. In the example code, we lead the user back to the App once he/she touched click the notification dialog.

This behavior should define before we launch the notification using the NofiticationManager.

 

Leave a comment