Cosc 4730

Download Cosc  4730

Post on 23-Feb-2016

44 views

Category:

Documents

0 download

Embed Size (px)

DESCRIPTION

Cosc 4730. Android Notifications Plus Alarms and B roadcastReceivers. Notifications. There are a couple of ways to notify users without interrupting what they are doing The first is Toast, use the factory method - PowerPoint PPT Presentation

TRANSCRIPT

Cosc 4755

Cosc 4730AndroidNotificationsNotificationsThere are a couple of ways to notify users without interrupting what they are doingThe first is Toast, use the factory methodToast.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.

Notifications (2)SnackBarSimple 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.

Notifications and Android APIsThe notifications have underground a lot of change.There is a completely deprecated method from 2.3.3 and belowThe newer method in 3.0 to 4.14.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.Status Bar NotificationsA 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).

Basics of notifications (all APIs)First get the NotificationManagerretrieve a reference to the NotificationManager with getSystemService() Create a Notification objectMin 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, doesnt 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.

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);

Canceling notificationsTo 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.Adding to the notification To add sounddefault soundnotification.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");Adding to the notification (2)Adding vibrationTo use the default patternnotification.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 in the AndroidManifest.xml Adding to the notification (3)Adding flashing lightsTo 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;Adding to the notification (4)FLAG_AUTO_CANCELflag Add this to the flags field to automatically cancel the notification after it is selected from the Notifications window. FLAG_INSISTENTflag Add this to the flags field to repeat the audio until the user responds. Should be flag "uh pick me! PICK ME!" FLAG_ONGOING_EVENTflag 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_CLEARflag Add this to the flags field to indicate that the notification should not be cleared by the "Clear notifications" buttonEmulator noteMany of the additional flags do nothing with the emulatorThere is no default sounds, it's set to silentno lights or vibration either, of course.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.NotificationCompatSo you can write the new notifications, this is a support library, call NotificationCompatThis allows us to create fancy notifications, but still work for the lower API.

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.Well cover wear and auto in advanced mobile course.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);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)Action ButtonsAdd the following to your notificationaddAction(int icon, CharSequence title, PendingIntent intent)Icon and title for the buttonThe 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.Expanded textThis 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();Expanded text (2)And we can get something like this

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.

Style of an inboxInbox 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();

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.

Well come back to next time after the broadcast receviers.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 notifications icon, but hides the notifications full content.VISIBILITY_PUBLIC: Shows the notifications full content.VISIBILITY_SECRET: Shows nothing, excluding even the notifications 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.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:

Demo codenotificiationDemo.zipnotificationDemo projectAll the different notifications listed in hereLots of buttons to try out each one.Alarms and the broadcastReceivernotificationDemo2 projectNeed first one installedSends to the broadcast receiverAnd uses an alarm to send to the broadcast receiverYou may also find http://developer.android.com/guide/topics