1 / 40

Cosc 4730

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

keena
Download Presentation

Cosc 4730

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Cosc 4730 Android Notifications Plus Alarms and BroadcastReceivers

  2. 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.

  3. 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+ (likely to change again after 4.4 or L) • 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.

  4. 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).

  5. 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.

  6. API 10 (2.3.3) and below NotificationManagermNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); int icon = R.drawable.icon; CharSequencetickerText = "Hello"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); //send the notification mNotificationManager.notify(ID_number, notification);

  7. Canceling notifications • To cancel a specific notification mNotificationManager.cancel(ID_number); • To cancel all of the notifications mNotificationManager.cancelAll(); • In newer API/support library. • .setAutoCancel(true) • which the user clicks it, it will clear.

  8. 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'sContentProvider: • notification.sound = Uri.withAppendedPath( Audio.Media.INTERNAL_CONTENT_URI, "6");

  9. 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

  10. 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;

  11. 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

  12. 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.

  13. 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.

  14. 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.

  15. How it works. • Create a NotificationCompat.Builder object and then once you have it configured, have it build the notification.

  16. Simple notification Notification 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 notification nm.notify(NotID, noti);

  17. 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(intargb, intonMs, intoffMs) • setSound(Uri sound) • setVibrate(long[] pattern)

  18. 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.

  19. 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 text Notification noti = new NotificationCompat.BigTextStyle(build) .bigText(“…”) //lots text here. .build();

  20. Expanded text (2) • And we can get something like this

  21. Expanded with image. • Same idea, except style is Notification noti = new NotificationCompat.BigPictureStyle(build) .bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.jelly_bean)) .build(); • Note two addAction(..) methods were added in the build.

  22. Style of an inbox • Inbox style and use addline and setSummaryText Notification noti = new NotificationCompat.InboxStyle(build) .addLine("Cupcake: Hi, how are you?") .addLine("Jelly Bean: Yummy") .setSummaryText("+999 more emails") .build();

  23. 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.

  24. Calendar

  25. Calendar object • It a pretty simple object. • Get an intance, which has the current time set. Calendar calendar= Calendar.getInstance(); • Use a get(..) and set(..) to change the information as needed. • Set using the following constants Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND • Say I want to set the calendar to 4:40am calendar.set(Calendar.HOUR_OF_DAY, 4); calendar.set(Calendar.MINUTE, 40); calendar.set(Calendar.SECOND, 0); • As note, if it is already passed 4:40am, there would be a problem later • Say I want to set it for 2 minutes from now. calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) +2);

  26. AlarmManager

  27. AlarmManager • These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. • We get an in AlarmManager service • Set an intent and pendingIntent for the activity (or say a broadcast receiver) to call. • A time in Milliseconds when to send the intent • And that we want a “wakeup call” at that time. • Get the AlarmManager • AlarmManageralarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

  28. Example code • Using the calendar object for 2 minutes later. • Create the intent and pendingIntent Intent notificationIntent = new Intent("edu.cs4730.notificationdemo.DisplayNotification"); PendingIntentcontentIntent = PendingIntent.getActivity(MainActivity.this, NotID, notificationIntent, 0); • Now set the alarm alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), contentIntent);

  29. Example code (2) • What is this: • Intent("edu.cs4730.notificationdemo.DisplayNotification"); • We could also just give a Activity name. • It comes from the manifest file where we describe the activity or broadcast receiver. This case an activity. <activity android:name=".DisplayNotification" … /> <intent-filter> <action android:name="edu.cs4730.notificationdemo.DisplayNotification" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>

  30. Finally! • The displayNotification activity is called when the alarm goes off. And it’s the displayNotification activity that now creates and notification.

  31. Broadcast Receiver

  32. BroadcastReceiver • Part of the android.content package. • Basically a listener, but for “broadcast” information. • Such as sms and other broadcast data. • Including our own broadcast intents. • Note, you don’t have access to most screen widgets in a broadcast receiver, except toast. • Override the onReceive(Context, Intent) method • The intent holds the information from the broadcast.

  33. BroadcastReceiver (2) • A broadcastReceiver can be registered into two ways: • Context.registerReceiver() in the “main” code • The receiver can be added and removed as needed. • Via a receiver tag in the AndroidManifest file. • will start up at boot. • We use this method for simplicity.

  34. Extend the BroadcastReceiver public class myReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { } } • Intent Tells you what it is, via the get getAction() method.

  35. AndroidManifest.xml • We also need to add the class. This is a receiver class so it may look something like this <receiver android:name=".myRecv"> <intent-filter> <action android:name="edu.cs4730.notificationdemo.broadNotification"/> </intent-filter> </receiver>

  36. As a Note • We could setup multiple intents to be received by the receiver, so we normally check the action to make sure it’s “ours”.

  37. Example public class myBroadcastReciever extends BroadcastReceiver { private static final String ACTION = "edu.cs4730.notificationdemo.broadNotification"; @Override public void onReceive(Context context, Intent intent) { String info= "no bundle"; if (intent.getAction().equals(ACTION)){ //is it our action Bundle extras = intent.getExtras(); if (extras != null) { info = extras.getString("mytype"); if (info == null) { info = "nothing"; } • Likely toast or start an activity or notification. Whatever is needed now. }}}

  38. 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.

  39. 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 • http://developer.android.com/reference/android/content/BroadcastReceiver.html • http://stackoverflow.com/questions/12372654/how-to-trigger-broadcast-receiver-from-notification • http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html

  40. Q A &

More Related