Download - Cosc 4730

Transcript
Page 1: Cosc  4730

Cosc 4730

AndroidNotifications

Page 2: Cosc  4730

Notifications

• There are a couple of ways to notify users without interrupting what they are doing

• The first is Toast, use the factory method– Toast.makeText(getBaseContext(), "Text to display

to user", Toast.LENGTH_SHORT).show();– getBaseContext() or getContext()

• Toast.LENGTH_SHORT or Toast.LENGTH_LONG is the duration it will be displayed.

Page 3: Cosc  4730

Notifications (2)

• SnackBar– Simple version

Snackbar.make(myView, "Hi there?", Snackbar.LENGTH_LONG) //or SHORT.show();

– With the response button Snackbar.make(myView, "Hi there?", Snackbar.LENGTH_LONG) //or SHORT .setAction("Undo?", SBonClickListener) //this line is optional..show();

• Where SBonClickListener is a standard OnClicklistener View.OnClickListener SBonClickListener = new View.OnClickListener(){ public void onClick (View v){ Toast.makeText(getActivity(),"You clicked undo", Toast.LENGTH_LONG).show(); } };

myView is first layout for the screen.

Page 4: Cosc  4730

Notifications and Android APIs

• The notifications have underground a lot of change.– There is a completely deprecated method from 2.3.3

and below– The newer method in 3.0 to 4.1– 4.1+ (and popups in 5.0)

• Wear and Auto variations as well for notifications.– And so much of this is used from the v4 support library.

• Things will not look the same, but at least you can use the same code.

Page 5: Cosc  4730

Status Bar Notifications• A status bar notification adds an icon

to the system's status bar (with an optional ticker-text message) and an expanded message in the "Notifications" window. – You can also configure the notification

to alert the user with a sound, a vibration, and flashing lights on the device.

• When the user selects the expanded message, Android fires an Intent that is defined by the notification (usually to launch an Activity).

Page 6: Cosc  4730

Basics of notifications (all APIs)• First get the NotificationManager

– retrieve a reference to the NotificationManager with getSystemService()

• Create a Notification object– Min requirements are an icon, text, and time of the event.

• Note, time of event is the time currently or in past.– For “future” events we have to use alarms, which is covered later.

• Pass it your Notification object with notify() via the notification manager.– Also send an ID number. This ID is used by your app, doesn’t have to

unique, but should be if you want more then one.– The system will show your notification on the status bar and the user

will interact with it.

Page 7: Cosc  4730

API 10 (2.3.3) and belowNotificationManager mNotificationManager =

(NotificationManager) getSystemService(NOTIFICATION_SERVICE);

int icon = R.drawable.icon;CharSequence tickerText = "Hello";long when = System.currentTimeMillis();

//Note, this method is removed in API 23 (marshmallow) Notification notification = new Notification(icon, tickerText,

when);//send the notificationmNotificationManager.notify(ID_number, notification);

Page 8: Cosc  4730

Canceling notifications

• To cancel a specific notificationmNotificationManager.cancel(ID_number);• To cancel all of the notificationsmNotificationManager.cancelAll();• In newer API/support library.– .setAutoCancel(true)• which the user clicks it, it will clear.

Page 9: Cosc  4730

Adding to the notification

• To add sound– default sound

• notification.defaults |= Notification.DEFAULT_SOUND;– To use a different sound with your notifications, pass a Uri

reference to the sound field. The following example uses a known audio file saved to the device SD card:• notification.sound =

Uri.parse("file:///sdcard/notification/ringer.mp3"); – the audio file is chosen from the internal MediaStore's

ContentProvider:• notification.sound =

Uri.withAppendedPath( Audio.Media.INTERNAL_CONTENT_URI, "6");

Page 10: Cosc  4730

Adding to the notification (2)

• Adding vibration– To use the default pattern• notification.defaults |= Notification.DEFAULT_VIBRATE;

– To define your own vibration pattern, pass an array of long values to the vibrate field:• long[] vibrate = {0,100,200,300};• notification.vibrate = vibrate;

– You'll need to add <uses-permission android:name="android.permission.VIBRATE"></uses-permission> in the AndroidManifest.xml

Page 11: Cosc  4730

Adding to the notification (3)• Adding flashing lights

– To use the default light setting, add "DEFAULT_LIGHTS" to the defaults field:• notification.defaults |= Notification.DEFAULT_LIGHTS;

– To define your own color and pattern, define a value for the ledARGB field (for the color), the ledOffMS field (length of time, in milliseconds, to keep the light off), the ledOnMS (length of time, in milliseconds, to keep the light on), and also add "FLAG_SHOW_LIGHTS" to the flags field:• notification.ledARGB = 0xff00ff00;• notification.ledOnMS = 300;• notification.ledOffMS = 1000;• notification.flags |= Notification.FLAG_SHOW_LIGHTS;

Page 12: Cosc  4730

Adding to the notification (4)• FLAG_AUTO_CANCEL

– flag Add this to the flags field to automatically cancel the notification after it is selected from the Notifications window.

• FLAG_INSISTENT– flag Add this to the flags field to repeat the audio until the user responds. – Should be flag "uh pick me! PICK ME!"

• FLAG_ONGOING_EVENT– flag Add this to the flags field to group the notification under the "Ongoing" title in

the Notifications window. – This indicates that the application is on-going — its processes is still running in the

background, even when the application is not visible (such as with music or a phone call).

• FLAG_NO_CLEAR– flag Add this to the flags field to indicate that the notification should not be cleared

by the "Clear notifications" button

Page 13: Cosc  4730

Emulator note

• Many of the additional flags do nothing with the emulator– There is no default sounds, it's set to silent– no lights or vibration either, of course.

Page 14: Cosc  4730

Notifications 3.0+

• We are going to use the support library at this point, so we code everything the same.

• Note, the Action Buttons (AddAction()) will not display on 4.1 and below.

Page 15: Cosc  4730

NotificationCompat

• So you can write the “new” notifications, this is a support library, call NotificationCompat– This allows us to create fancy notifications, but still

work for the lower API.

Page 16: Cosc  4730

How it works.

• Create a NotificationCompat.Builder object and then once you have it configured, have it build the notification.– use the NotificationCompat from the support lib v4

– import android.support.v4.app.NotificationCompat;– import android.support.v4.app.NotificationManagerCompat;

– Side note, this also allows notifications to show up on android wear devices as well.• Maybe Android Auto too.• We’ll cover wear and auto in advanced mobile course.

Page 17: Cosc  4730

Simple notificationNotification noti = new NotificationCompat.Builder(getApplicationContext()) .setSmallIcon(R.drawable.ic_launcher) .setWhen(System.currentTimeMillis()) //When the event occurred, now .setTicker("Message on status bar") //message shown on the status bar .setContentTitle("Marquee Message") //Title message top row. .setContentText("Icon and Message") //second row .setContentIntent(contentIntent) //what activity to open. .setAutoCancel(true) //allow auto cancel when pressed. .build(); //finally build and return a Notification.• Show the notificationnm.notify(NotID, noti);

Page 18: Cosc  4730

Lights, sounds, etc.

• Just like before with can use the defaults– .setDefaults(Notification.DEFAULT_LIGHTS |

Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND);

• Or use the newer methods to choose your own.– setLights(int argb, int onMs, int offMs)– setSound(Uri sound)– setVibrate(long[] pattern)

Page 19: Cosc  4730

Action Buttons

• Add the following to your notification• addAction(int icon, CharSequence title,

PendingIntent intent)– Icon and title for the button– The intent should be completely different intent

from the setContentIntent(intent), so you know which button was clicked.• See the example code, where I have four intents for the

example with three buttons.

Page 20: Cosc  4730

Expanded text

• This one we need change the style of the notification. First use the builder to create the default

• NotificationCompat.Builder build = new NotificationCompat.Builder(ge …;

• Now change to another style and add more textNotification noti = new NotificationCompat.BigTextStyle(build)

.bigText(“…”) //lots text here.

.build();

Page 21: Cosc  4730

Expanded text (2)

• And we can get something like this

Page 22: Cosc  4730

Expanded with image.

• Same idea, except style isNotification noti = new NotificationCompat.BigPictureStyle(build).bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.jelly_bean)).build();• Note two addAction(..) methodswere added in the build.

Page 23: Cosc  4730

Style of an inbox• Inbox style and use addline and setSummaryTextNotification noti = new NotificationCompat.InboxStyle(build) .addLine("Cupcake: Hi, how are you?")

.addLine("Jelly Bean: Yummy")

.setSummaryText("+999 more emails")

.build();

Page 24: Cosc  4730

But I want to notify a user later!

• There is no native way to that with the notifications.

• You need to use an AlarmManager and calendar object and a broadcast receiver.

• We’ll come back to next time after the broadcast receviers.

Page 25: Cosc  4730

Lastly android 5 notifications.• In Lollipop three new pieces were added.

– setVisibility() and specify one of these values:– What shows on the lock screen.– VISIBILITY_PRIVATE: Shows basic information, such as the notification’s icon, but

hides the notification’s full content.– VISIBILITY_PUBLIC: Shows the notification’s full content.– VISIBILITY_SECRET: Shows nothing, excluding even the notification’s icon.

– addPerson(): Enables you to add one or more people who are relevant to a notification.

– setPriority(): Marks the notification as more or less important than normal notifications. • Notifications with the priority field set to PRIORITY_MAX or

PRIORITY_HIGH appear in a small floating window if the notification also has sound or vibration.

Page 26: Cosc  4730

Lastly android 5 notifications (2)

• Adding the following (with NotificationCompat)

.setPriority(Notification.PRIORITY_MAX)

.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})– We can produce this kind of notification:

Page 27: Cosc  4730

Demo code• notificiationDemo.zip– notificationDemo project

• All the different notifications listed in here– Lots of buttons to try out each one.

• Alarms and the broadcastReceiver– notificationDemo2 project

• Need first one installed• Sends to the broadcast receiver• And uses an alarm to send to the broadcast receiver

• You may also find http://developer.android.com/guide/topics/ui/notifiers/notifications.html helpful.

Page 28: Cosc  4730

References • http://

stackoverflow.com/questions/1198558/how-to-send-parameters-from-a-notification-click-to-an-activity

• http://mobiforge.com/developing/story/displaying-status-bar-notifications-android• http://

developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html

• http://mobiforge.com/developing/story/displaying-status-bar-notifications-android • http://

stackoverflow.com/questions/12006724/set-a-combination-of-vibration-lights-or-sound-for-a-notification-in-android

• http://developer.android.com/reference/android/app/Notification.html • Android 5 notifications information:

– http://developer.android.com/about/versions/android-5.0.html#Notifications– http://www.intertech.com/Blog/android-development-tutorial-lollipop-notifications/

Page 29: Cosc  4730

QA&


Top Related