SlideShare a Scribd company logo
1 of 31
Download to read offline
Android
Notifications
222
NotificationsNotifications
2
What is a Notification?
A notification is a short message briefly displayed on the status line.
It typically announces the happening of an special event for which a
trigger has been set.
After opening the Notification Panel the user may choose to click on a
selection and execute an associated activity.
333
NotificationsNotifications
3
What is a Notification?
Notification shown
on the status line
Drag down
Click on
Notification
Panel to
execute
associated
application
444
NotificationsNotifications
4
Notification Manager
This class notifies the user of events that happen in the background.
Notifications can take different forms:
1. A persistent icon that goes in the status bar and is accessible through the
launcher, (when the user selects it, a designated Intent can be launched),
2. Turning on or flashing LEDs on the device, or
3. Alerting the user by flashing the backlight, playing a sound, or vibrating.
555
NotificationsNotifications –– Since Jelly Bean 4.0Since Jelly Bean 4.0
5
Base Layout
All notifications include in their MINIMUM configurations three parts:
1. the sending application's notification icon or the sender's photo a
notification title and message
2. a timestamp
3. a secondary icon to identify the sending application when the senders
image is shown for the main icon
Optional Entries
1. Additional lines
2. Up to three actions
3. A summary line
666
NotificationsNotifications –– Since Jelly Bean 4.0Since Jelly Bean 4.0
6
Extended Layout
Sender’s
Icon / Photo
Extra lines
Up to 3
Actions to
call
Summary
Activity to
be called
777
NotificationsNotifications
7
Notification Manager
You do not instantiate this class directly; instead, retrieve it through
getSystemService ( String ).
Example:
String servName = Context.NOTIFICATION_SERVICE;
notificationManager = (NotificationManager)
getSystemService (servName);
888
NotificationsNotifications
8
Notification Builder
A convenient way to set up various fields of a Notification
Example:
Notification noti = new Notification.Builder(Context)
.setContentTitle(“Important message for you...”)
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build();
999
NotificationsNotifications
9
Example
10
NotificationsNotifications
Example
11
NotificationsNotifications
Example
12
NotificationsNotifications
Example: MainActivity
package com.example.mynotificationmanager;
import . . .
public class MainActivity extends Activity implements OnClickListener {
NotificationManager notificationManager;
final int NOTIFICATION_ID = 12345;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btnBig).setOnClickListener(this);
findViewById(R.id.btnCancel).setOnClickListener(this);
}// onCreate
@SuppressLint("NewApi")
public void createBigNotification(View view) {
Intent intent = new Intent(this, NotificationReceiverActivity.class);
intent.putExtra("callerIntent", "main");
intent.putExtra("notificationID", NOTIFICATION_ID);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
13
NotificationsNotifications
Example: MainActivity
// better way to do previous work
PendingIntent pIntent1 = makePendingIntent(
NotificationReceiverActivity1.class, "Action1");
PendingIntent pIntent2 = makePendingIntent(
NotificationReceiverActivity2.class, "Action2");
PendingIntent pIntent3 = makePendingIntent(
NotificationReceiverActivity3.class, "Action3");
// a bitmap to be added in the notification view
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.my_large_bitmap);
Notification.Builder baseNotification = new Notification.Builder(this)
.setContentTitle("TITLE goes here ...")
.setContentText("Second Line of text goes here")
.setTicker("Ticker tape1...Ticker tape2...")
.addAction(R.drawable.icon1, "Action1", pIntent1)
.addAction(R.drawable.icon2, "Action2", pIntent2)
.addAction(R.drawable.icon3, "Action3", pIntent3)
.setSmallIcon(R.drawable.icon0)
.setLargeIcon(myBitmap)
.setLights(0xffcc00, 1000, 500)
.setContentIntent(pIntent) ;
14
NotificationsNotifications
Example: MainActivity
Notification noti = new Notification.InboxStyle(baseNotification)
.addLine("Line-1")
.addLine("Line-2")
.addLine("Line-2")
.setSummaryText("SUMMARY-Line-1 here")
.build();
notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
// notification ID is 12345
notificationManager.notify(12345, noti);
}// createBigNotification
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnBig:
createBigNotification(v);
break;
15
NotificationsNotifications
Example: MainActivity
case R.id.btnCancel :
try {
if ( notificationManager != null){
notificationManager.cancel(NOTIFICATION_ID);
}
} catch (Exception e) {
Log.e("<<MAIN>>", e.getMessage() );
}
break;
}
}// onClick
public PendingIntent makePendingIntent(Class partnerClass, String callerName)
{
Intent intent = new Intent(this, partnerClass);
intent.putExtra("callerIntent", callerName);
intent.putExtra("notificationID", NOTIFICATION_ID);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
return pIntent;
}
}// class
16
NotificationsNotifications
Example: NotificationReceiverActivity
package com.example.mynotificationmanager;
import . . .
public class NotificationReceiverActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
String callerName = getIntent()
.getStringExtra("callerIntent");
Toast.makeText(this, "Called by: " + callerName, 1).show();
}
}
17
NotificationsNotifications
Example: Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mynotificationmanager"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" ><activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NotificationReceiverActivity"
android:icon="@drawable/icon0" >
</activity>
18
NotificationsNotifications
Example: Manifest
<activity android:name=".NotificationReceiverActivity1"
android:icon="@drawable/icon1" >
</activity>
<activity android:name=".NotificationReceiverActivity2"
android:icon="@drawable/icon2" >
</activity>
<activity android:name=".NotificationReceiverActivity3"
android:icon="@drawable/icon3" >
</activity>
</application>
</manifest>
19
NotificationsNotifications
Example - Layout: main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnBig"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Big Notification"
android:ems="20" >
</Button>
<Button
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel Notification"
android:ems="20" >
</Button>
</LinearLayout>
20
NotificationsNotifications
Example - Layout: main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Called from the MASTER notification" >
</TextView>
</LinearLayout>
212121
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
21
Notification
This class represents how a persistent notification is to be presented to
the user using the NotificationManager.
public Notification (int icon, CharSequence tickerText, long when)
Parameters
icon The resource id of the icon to put in the status bar.
tickerText The text that flows by in the status bar when the notification
first activates.
when The time to show in the time field.
In the System.currentTimeMillis timebase.
22222222
Notification - Methods
public void notify (int id, Notification notification)
Places a persistent notification on the status bar.
Parameters
id An identifier for this notification unique within
your application.
notification A Notification object describing how to notify the
user, other than the view you're providing.
Must not be null.
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
23232323
Notification – Methods
public void setLatestEventInfo (
Context context, CharSequence contentTitle,
CharSequence contentText, PendingIntent contentIntent)
Sets the contentView field to be a view with the standard "Latest Event"
layout.
Parameters
context The context for your application / activity.
contentTitle The title that goes in the expanded entry.
contentText The text that goes in the expanded entry.
contentIntent The intent to launch when the user clicks the expanded
notification.
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
24242424
Notification – Methods
public void cancel ( int id )
public void cancelAll ( )
Cancel a previously shown notification. If it's transient, the view will be
hidden. If it's persistent, it will be removed from the status bar.
Parameters
Id An identifier for this notification unique within your application.
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
25252525
Example.
Produce a notification. Allow the user to click on the Notification Panel
and execute appropriate activity to attend the message.
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
26262626
Example - Layouts
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/myLinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff000066"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >
<Button
android:id="@+id/btnGo"
android:layout_width="106dp"
android:layout_height="61dp"
android:layout_margin="10dp"
android:text=" Show Notification " >
</Button>
<Button
android:id="@+id/btnStop"
android:layout_width="106dp"
android:layout_height="61dp"
android:layout_margin="10dp"
android:text=" Cancel Notification " >
</Button>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/main2LinLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff660000"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/an
droid"
>
<TextView
android:id="@+id/widget29"
android:layout_width="251dp"
android:layout_height="69dp"
android:text="Hola this is screen 2 - Layout:main2.xml"
>
</TextView>
</LinearLayout>
main.xml main2.xml
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
27272727
Example – Manifest /drawable
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cis493.demos"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"
android:label="@string/app_name">
<activity android:name=".NotifyDemo1"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NotifyHelper" >
</activity>
</application>
<uses-sdk android:minSdkVersion="4" />
</manifest>
btn_star_big_on_selected.png
Note:
Obtain the icon from the folder
C:Androidplatformsandroid-
1.xdataresdrawable
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
28282828
Example – Create & Cancel a Notification
package cis493.demos;
import . . .
public class NotifyDemo1 extends Activity {
Button btnGo;
Button btnStop;
int notificationId = 1;
NotificationManager notificationManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
29292929
Example – Create & Cancel a Notification
btnGo = (Button)findViewById(R.id.btnGo);
btnGo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//define a notification manager
String serName = Context.NOTIFICATION_SERVICE;
notificationManager = (NotificationManager)getSystemService(serName);
//define notification using: icon, text, and timing.
int icon = R.drawable.btn_star_big_on_selected;
String tickerText = "1. My Notification TickerText";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
//configure appearance of the notification
String extendedTitle = "2. My Extended Title";
String extendedText = "3. This is an extended and very important message";
Intent intent = new Intent(getApplicationContext(), NotifyHelper.class);
intent.putExtra("extendedText", extendedText);
intent.putExtra("extendedTitle", extendedTitle);
PendingIntent launchIntent =
PendingIntent.getActivity(getApplicationContext(),0,intent,0);
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
30303030
Example – Create & Cancel a Notification
notification.setLatestEventInfo(getApplicationContext(),
extendedTitle, extendedText,
launchIntent);
//trigger notification
notificationId = 1;
notificationManager.notify(notificationId, notification);
}//click
});
btnStop = (Button)findViewById(R.id.btnStop);
btnStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//canceling a notification
notificationId = 1;
notificationManager.cancel(notificationId);
}
});
}//onCreate
}//NotifyDemo1
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
31313131
Example - SubActivity – Attending the Notification
package cis493.demos;
Import. . .
public class NotifyHelper extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Intent myData = getIntent();
// extract the extra-data in the Notification
String msg = myData.getStringExtra("extendedTitle") + "n"
+ myData.getStringExtra("extendedText");
Toast.makeText(getApplicationContext(), msg, 1).show();
}
}
Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)

More Related Content

Viewers also liked

Ch3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes RécursivesCh3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes Récursiveslotfibenromdhane
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Ch1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de BaseCh1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de Baselotfibenromdhane
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJosé Paumard
 
Ch2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - RécursivitéCh2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - Récursivitélotfibenromdhane
 
Ch7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-CopmlétudeCh7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-Copmlétudelotfibenromdhane
 
Ch5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de TriCh5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de Trilotfibenromdhane
 
JDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne TourJDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne TourJosé Paumard
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8LivePerson
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJosé Paumard
 
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautésAlphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautésAlphorm
 
Alphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server FacesAlphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server FacesAlphorm
 
Alphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certificationAlphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certificationAlphorm
 
Alphorm.com Java 8: les nouveautés
Alphorm.com Java 8: les nouveautésAlphorm.com Java 8: les nouveautés
Alphorm.com Java 8: les nouveautésAlphorm
 
Alphorm.com Formation Java, les fondamentaux
Alphorm.com Formation Java, les fondamentaux Alphorm.com Formation Java, les fondamentaux
Alphorm.com Formation Java, les fondamentaux Alphorm
 

Viewers also liked (19)

Cats
CatsCats
Cats
 
Functional programming in java
Functional programming in javaFunctional programming in java
Functional programming in java
 
Ch3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes RécursivesCh3 Algorthmique Avancée - Méthodes Récursives
Ch3 Algorthmique Avancée - Méthodes Récursives
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Functional Programming in JAVA 8
Functional Programming in JAVA 8Functional Programming in JAVA 8
Functional Programming in JAVA 8
 
Ch1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de BaseCh1 Algorthmique Avancée - Rappel & Notions de Base
Ch1 Algorthmique Avancée - Rappel & Notions de Base
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
 
Ch2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - RécursivitéCh2 Algorthmique Avancée - Récursivité
Ch2 Algorthmique Avancée - Récursivité
 
Ch7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-CopmlétudeCh7 algorithmes NP-Copmlétude
Ch7 algorithmes NP-Copmlétude
 
Ch5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de TriCh5 Algorthmique Avancée - Algorithme de Tri
Ch5 Algorthmique Avancée - Algorithme de Tri
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
JDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne TourJDK 8, lambdas, streams, collectors - Bretagne Tour
JDK 8, lambdas, streams, collectors - Bretagne Tour
 
Functional programming with Java 8
Functional programming with Java 8Functional programming with Java 8
Functional programming with Java 8
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautésAlphorm.com Formation Autodesk Revit 2018 : Les nouveautés
Alphorm.com Formation Autodesk Revit 2018 : Les nouveautés
 
Alphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server FacesAlphorm.com Formation Java Server Faces
Alphorm.com Formation Java Server Faces
 
Alphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certificationAlphorm.com Formation CND 2/2: Réussir la certification
Alphorm.com Formation CND 2/2: Réussir la certification
 
Alphorm.com Java 8: les nouveautés
Alphorm.com Java 8: les nouveautésAlphorm.com Java 8: les nouveautés
Alphorm.com Java 8: les nouveautés
 
Alphorm.com Formation Java, les fondamentaux
Alphorm.com Formation Java, les fondamentaux Alphorm.com Formation Java, les fondamentaux
Alphorm.com Formation Java, les fondamentaux
 

Similar to Notifications

Session #8 adding magic to your app
Session #8  adding magic to your appSession #8  adding magic to your app
Session #8 adding magic to your appVitali Pekelis
 
Android notification
Android notificationAndroid notification
Android notificationKrazy Koder
 
Local Notification Tutorial
Local Notification TutorialLocal Notification Tutorial
Local Notification TutorialKetan Raval
 
Android Wearables ii
Android Wearables iiAndroid Wearables ii
Android Wearables iiKetan Raval
 
Android Wear – IO Extended
Android Wear – IO ExtendedAndroid Wear – IO Extended
Android Wear – IO ExtendedDouglas Drumond
 
Dicoding Developer Coaching #22: Android | Cara Membuat Notifikasi di Aplikas...
Dicoding Developer Coaching #22: Android | Cara Membuat Notifikasi di Aplikas...Dicoding Developer Coaching #22: Android | Cara Membuat Notifikasi di Aplikas...
Dicoding Developer Coaching #22: Android | Cara Membuat Notifikasi di Aplikas...DicodingEvent
 
Android Training (Notifications)
Android Training (Notifications)Android Training (Notifications)
Android Training (Notifications)Khaled Anaqwa
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptxGood657694
 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in AndroidPerfect APK
 
Developing for android wear
Developing for android wearDeveloping for android wear
Developing for android wearThomas Oldervoll
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVASrajan Shukla
 
Introduction to Android Wear
Introduction to Android WearIntroduction to Android Wear
Introduction to Android Weargabrielemariotti
 
What's New in User Notifications Framework - WWDC16. Meetup @Wantedly with 日本...
What's New in User Notifications Framework - WWDC16. Meetup @Wantedly with 日本...What's New in User Notifications Framework - WWDC16. Meetup @Wantedly with 日本...
What's New in User Notifications Framework - WWDC16. Meetup @Wantedly with 日本...将之 小野
 
Android Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and IntentAndroid Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and Intentadmin220812
 
Creating a Facebook Clone - Part XIV - Transcript.pdf
Creating a Facebook Clone - Part XIV - Transcript.pdfCreating a Facebook Clone - Part XIV - Transcript.pdf
Creating a Facebook Clone - Part XIV - Transcript.pdfShaiAlmog1
 

Similar to Notifications (20)

Notification android
Notification androidNotification android
Notification android
 
Session #8 adding magic to your app
Session #8  adding magic to your appSession #8  adding magic to your app
Session #8 adding magic to your app
 
Android notification
Android notificationAndroid notification
Android notification
 
Local Notification Tutorial
Local Notification TutorialLocal Notification Tutorial
Local Notification Tutorial
 
Android Wear Development
Android Wear DevelopmentAndroid Wear Development
Android Wear Development
 
Android Wearables ii
Android Wearables iiAndroid Wearables ii
Android Wearables ii
 
Android Wear – IO Extended
Android Wear – IO ExtendedAndroid Wear – IO Extended
Android Wear – IO Extended
 
Android action bar and notifications-chapter16
Android action bar and notifications-chapter16Android action bar and notifications-chapter16
Android action bar and notifications-chapter16
 
Dicoding Developer Coaching #22: Android | Cara Membuat Notifikasi di Aplikas...
Dicoding Developer Coaching #22: Android | Cara Membuat Notifikasi di Aplikas...Dicoding Developer Coaching #22: Android | Cara Membuat Notifikasi di Aplikas...
Dicoding Developer Coaching #22: Android | Cara Membuat Notifikasi di Aplikas...
 
Android Training (Notifications)
Android Training (Notifications)Android Training (Notifications)
Android Training (Notifications)
 
Introduction to Android Wear
Introduction to Android WearIntroduction to Android Wear
Introduction to Android Wear
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
Android wear (coding)
Android wear (coding)Android wear (coding)
Android wear (coding)
 
BroadcastReceivers in Android
BroadcastReceivers in AndroidBroadcastReceivers in Android
BroadcastReceivers in Android
 
Developing for android wear
Developing for android wearDeveloping for android wear
Developing for android wear
 
Event Handling in JAVA
Event Handling in JAVAEvent Handling in JAVA
Event Handling in JAVA
 
Introduction to Android Wear
Introduction to Android WearIntroduction to Android Wear
Introduction to Android Wear
 
What's New in User Notifications Framework - WWDC16. Meetup @Wantedly with 日本...
What's New in User Notifications Framework - WWDC16. Meetup @Wantedly with 日本...What's New in User Notifications Framework - WWDC16. Meetup @Wantedly with 日本...
What's New in User Notifications Framework - WWDC16. Meetup @Wantedly with 日本...
 
Android Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and IntentAndroid Event and IntentAndroid Event and Intent
Android Event and IntentAndroid Event and Intent
 
Creating a Facebook Clone - Part XIV - Transcript.pdf
Creating a Facebook Clone - Part XIV - Transcript.pdfCreating a Facebook Clone - Part XIV - Transcript.pdf
Creating a Facebook Clone - Part XIV - Transcript.pdf
 

Notifications

  • 2. 222 NotificationsNotifications 2 What is a Notification? A notification is a short message briefly displayed on the status line. It typically announces the happening of an special event for which a trigger has been set. After opening the Notification Panel the user may choose to click on a selection and execute an associated activity.
  • 3. 333 NotificationsNotifications 3 What is a Notification? Notification shown on the status line Drag down Click on Notification Panel to execute associated application
  • 4. 444 NotificationsNotifications 4 Notification Manager This class notifies the user of events that happen in the background. Notifications can take different forms: 1. A persistent icon that goes in the status bar and is accessible through the launcher, (when the user selects it, a designated Intent can be launched), 2. Turning on or flashing LEDs on the device, or 3. Alerting the user by flashing the backlight, playing a sound, or vibrating.
  • 5. 555 NotificationsNotifications –– Since Jelly Bean 4.0Since Jelly Bean 4.0 5 Base Layout All notifications include in their MINIMUM configurations three parts: 1. the sending application's notification icon or the sender's photo a notification title and message 2. a timestamp 3. a secondary icon to identify the sending application when the senders image is shown for the main icon Optional Entries 1. Additional lines 2. Up to three actions 3. A summary line
  • 6. 666 NotificationsNotifications –– Since Jelly Bean 4.0Since Jelly Bean 4.0 6 Extended Layout Sender’s Icon / Photo Extra lines Up to 3 Actions to call Summary Activity to be called
  • 7. 777 NotificationsNotifications 7 Notification Manager You do not instantiate this class directly; instead, retrieve it through getSystemService ( String ). Example: String servName = Context.NOTIFICATION_SERVICE; notificationManager = (NotificationManager) getSystemService (servName);
  • 8. 888 NotificationsNotifications 8 Notification Builder A convenient way to set up various fields of a Notification Example: Notification noti = new Notification.Builder(Context) .setContentTitle(“Important message for you...”) .setContentText(subject) .setSmallIcon(R.drawable.new_mail) .setLargeIcon(aBitmap) .build();
  • 12. 12 NotificationsNotifications Example: MainActivity package com.example.mynotificationmanager; import . . . public class MainActivity extends Activity implements OnClickListener { NotificationManager notificationManager; final int NOTIFICATION_ID = 12345; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); findViewById(R.id.btnBig).setOnClickListener(this); findViewById(R.id.btnCancel).setOnClickListener(this); }// onCreate @SuppressLint("NewApi") public void createBigNotification(View view) { Intent intent = new Intent(this, NotificationReceiverActivity.class); intent.putExtra("callerIntent", "main"); intent.putExtra("notificationID", NOTIFICATION_ID); PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
  • 13. 13 NotificationsNotifications Example: MainActivity // better way to do previous work PendingIntent pIntent1 = makePendingIntent( NotificationReceiverActivity1.class, "Action1"); PendingIntent pIntent2 = makePendingIntent( NotificationReceiverActivity2.class, "Action2"); PendingIntent pIntent3 = makePendingIntent( NotificationReceiverActivity3.class, "Action3"); // a bitmap to be added in the notification view Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_large_bitmap); Notification.Builder baseNotification = new Notification.Builder(this) .setContentTitle("TITLE goes here ...") .setContentText("Second Line of text goes here") .setTicker("Ticker tape1...Ticker tape2...") .addAction(R.drawable.icon1, "Action1", pIntent1) .addAction(R.drawable.icon2, "Action2", pIntent2) .addAction(R.drawable.icon3, "Action3", pIntent3) .setSmallIcon(R.drawable.icon0) .setLargeIcon(myBitmap) .setLights(0xffcc00, 1000, 500) .setContentIntent(pIntent) ;
  • 14. 14 NotificationsNotifications Example: MainActivity Notification noti = new Notification.InboxStyle(baseNotification) .addLine("Line-1") .addLine("Line-2") .addLine("Line-2") .setSummaryText("SUMMARY-Line-1 here") .build(); notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Hide the notification after its selected noti.flags |= Notification.FLAG_AUTO_CANCEL; // notification ID is 12345 notificationManager.notify(12345, noti); }// createBigNotification @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnBig: createBigNotification(v); break;
  • 15. 15 NotificationsNotifications Example: MainActivity case R.id.btnCancel : try { if ( notificationManager != null){ notificationManager.cancel(NOTIFICATION_ID); } } catch (Exception e) { Log.e("<<MAIN>>", e.getMessage() ); } break; } }// onClick public PendingIntent makePendingIntent(Class partnerClass, String callerName) { Intent intent = new Intent(this, partnerClass); intent.putExtra("callerIntent", callerName); intent.putExtra("notificationID", NOTIFICATION_ID); PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0); return pIntent; } }// class
  • 16. 16 NotificationsNotifications Example: NotificationReceiverActivity package com.example.mynotificationmanager; import . . . public class NotificationReceiverActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.result); String callerName = getIntent() .getStringExtra("callerIntent"); Toast.makeText(this, "Called by: " + callerName, 1).show(); } }
  • 17. 17 NotificationsNotifications Example: Manifest <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mynotificationmanager" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="14" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" ><activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".NotificationReceiverActivity" android:icon="@drawable/icon0" > </activity>
  • 18. 18 NotificationsNotifications Example: Manifest <activity android:name=".NotificationReceiverActivity1" android:icon="@drawable/icon1" > </activity> <activity android:name=".NotificationReceiverActivity2" android:icon="@drawable/icon2" > </activity> <activity android:name=".NotificationReceiverActivity3" android:icon="@drawable/icon3" > </activity> </application> </manifest>
  • 19. 19 NotificationsNotifications Example - Layout: main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/btnBig" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Create Big Notification" android:ems="20" > </Button> <Button android:id="@+id/btnCancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Cancel Notification" android:ems="20" > </Button> </LinearLayout>
  • 20. 20 NotificationsNotifications Example - Layout: main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/txtMsg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Called from the MASTER notification" > </TextView> </LinearLayout>
  • 21. 212121 Notifications (Before SDK 4.0)Notifications (Before SDK 4.0) 21 Notification This class represents how a persistent notification is to be presented to the user using the NotificationManager. public Notification (int icon, CharSequence tickerText, long when) Parameters icon The resource id of the icon to put in the status bar. tickerText The text that flows by in the status bar when the notification first activates. when The time to show in the time field. In the System.currentTimeMillis timebase.
  • 22. 22222222 Notification - Methods public void notify (int id, Notification notification) Places a persistent notification on the status bar. Parameters id An identifier for this notification unique within your application. notification A Notification object describing how to notify the user, other than the view you're providing. Must not be null. Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
  • 23. 23232323 Notification – Methods public void setLatestEventInfo ( Context context, CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) Sets the contentView field to be a view with the standard "Latest Event" layout. Parameters context The context for your application / activity. contentTitle The title that goes in the expanded entry. contentText The text that goes in the expanded entry. contentIntent The intent to launch when the user clicks the expanded notification. Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
  • 24. 24242424 Notification – Methods public void cancel ( int id ) public void cancelAll ( ) Cancel a previously shown notification. If it's transient, the view will be hidden. If it's persistent, it will be removed from the status bar. Parameters Id An identifier for this notification unique within your application. Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
  • 25. 25252525 Example. Produce a notification. Allow the user to click on the Notification Panel and execute appropriate activity to attend the message. Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
  • 26. 26262626 Example - Layouts <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/myLinearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff000066" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" > <Button android:id="@+id/btnGo" android:layout_width="106dp" android:layout_height="61dp" android:layout_margin="10dp" android:text=" Show Notification " > </Button> <Button android:id="@+id/btnStop" android:layout_width="106dp" android:layout_height="61dp" android:layout_margin="10dp" android:text=" Cancel Notification " > </Button> </LinearLayout> <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:id="@+id/main2LinLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff660000" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/an droid" > <TextView android:id="@+id/widget29" android:layout_width="251dp" android:layout_height="69dp" android:text="Hola this is screen 2 - Layout:main2.xml" > </TextView> </LinearLayout> main.xml main2.xml Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
  • 27. 27272727 Example – Manifest /drawable <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cis493.demos" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".NotifyDemo1" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".NotifyHelper" > </activity> </application> <uses-sdk android:minSdkVersion="4" /> </manifest> btn_star_big_on_selected.png Note: Obtain the icon from the folder C:Androidplatformsandroid- 1.xdataresdrawable Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
  • 28. 28282828 Example – Create & Cancel a Notification package cis493.demos; import . . . public class NotifyDemo1 extends Activity { Button btnGo; Button btnStop; int notificationId = 1; NotificationManager notificationManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
  • 29. 29292929 Example – Create & Cancel a Notification btnGo = (Button)findViewById(R.id.btnGo); btnGo.setOnClickListener(new OnClickListener() { public void onClick(View v) { //define a notification manager String serName = Context.NOTIFICATION_SERVICE; notificationManager = (NotificationManager)getSystemService(serName); //define notification using: icon, text, and timing. int icon = R.drawable.btn_star_big_on_selected; String tickerText = "1. My Notification TickerText"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); //configure appearance of the notification String extendedTitle = "2. My Extended Title"; String extendedText = "3. This is an extended and very important message"; Intent intent = new Intent(getApplicationContext(), NotifyHelper.class); intent.putExtra("extendedText", extendedText); intent.putExtra("extendedTitle", extendedTitle); PendingIntent launchIntent = PendingIntent.getActivity(getApplicationContext(),0,intent,0); Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
  • 30. 30303030 Example – Create & Cancel a Notification notification.setLatestEventInfo(getApplicationContext(), extendedTitle, extendedText, launchIntent); //trigger notification notificationId = 1; notificationManager.notify(notificationId, notification); }//click }); btnStop = (Button)findViewById(R.id.btnStop); btnStop.setOnClickListener(new OnClickListener() { public void onClick(View v) { //canceling a notification notificationId = 1; notificationManager.cancel(notificationId); } }); }//onCreate }//NotifyDemo1 Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)
  • 31. 31313131 Example - SubActivity – Attending the Notification package cis493.demos; Import. . . public class NotifyHelper extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main2); Intent myData = getIntent(); // extract the extra-data in the Notification String msg = myData.getStringExtra("extendedTitle") + "n" + myData.getStringExtra("extendedText"); Toast.makeText(getApplicationContext(), msg, 1).show(); } } Notifications (Before SDK 4.0)Notifications (Before SDK 4.0)