SlideShare ist ein Scribd-Unternehmen logo
1 von 8
"Android Application Development Company India" www.letsnurture.com
Local Notification Tutorial
"Android Application Development Company India" www.letsnurture.com
Android Notifications
Android allows to put notification into the titlebar of your application. The user
can expand the notification bar and by selecting the notification the user can
trigger another activity.
Here we have used NotificationCompat because on older platform versions that
don't offer expanded notifications, methods that depend on expanded
notifications have no effect.
For example, action buttons won't appear on platforms prior to Android 4.1.
Action buttons depend on expanded notifications, which are only available in
Android 4.1 and later. So provide support support lib v4
follow below step to create Notification with different style.
Step 1: Create Notification Builder
Create Notification Builder using NotificationCompat.Builder.build().
NotificationCompat.Builder. Used for set various Notification Properties like
its small and large icons,title priority ...
// Building the notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
Step 2 : Setting Notification Properties
Once you have Builder object, you can set its Notification properties using
Builder object as per your requirement. But this is mandatory to set at least
following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("simple notification")
"Android Application Development Company India" www.letsnurture.com
.setContentText("the text of the simple notification")
Step 3 - Attach Action to Notification
This is an optional part and required if you want to attach an action with the
notification. An action allows users to redirecte from the notification to an
Activity in application, where they can look at one or more events or do further
work.
The action can be achived by a PendingIntent containing an Intent that starts
an Activity in your application. To associate the PendingIntent with a gesture,
call the appropriate method of NotificationCompat.Builder. For example, if you
want to start Activity when the user clicks the notification text in the
notification drawer, you add the PendingIntent by calling setContentIntent().
// Pending intent to the notification manager
PendingIntent resultPending = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
// Building the notification
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("simple notification")
.setContentText("the text of the simple notification")
.setContentIntent(resultPending);// attach action here.
Step 4 : Issue the notifacation
You pass the Notification object to the system by calling
NotificationManager.notify() to send your notification. Make sure you call
NotificationCompat.Builder.build() method on builder object before notifying
it. This method combines all of the options that have been set and return a
newNotification object.
// mId allows you to update the notification later on.
NotificationManager mNotificationManager.notify(10, mBuilder.build());
This Method post a notification to be shown in the status bar. If a notification
with the same id has already been posted by application and has not yet been
canceled, it will be replaced by the updated information.
"Android Application Development Company India" www.letsnurture.com
Set Notification Priority
You can set the priority of a notification. The priority acts as a hint to the
device UI about how the notification should be displayed. To set a notification's
priority, callNotificationCompat.Builder.setPriority() and pass in one of the
NotificationCompat priority constants. There are five priority levels, ranging
from PRIORITY_MIN (-2) to PRIORITY_MAX (2); if not set, the priority
defaults to PRIORITY_DEFAULT (0).
Here we have created differet kind of Notification.
Create a big view style to a notification
To Create Notification in a big view when it's expanded, first create a
NotificationCompat.Builder object with the normal view. Next, call
Builder.setStyle() with a big view style object as its argument.
Note: expanded notifications are not available on platforms prior to Android
4.1.how to handle notifications for Android 4.1 and for earlier platforms, read
the section Handling compatibility.
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// Building the expandable content
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
String lorem = context.getResources()
.getString(R.string.long_lorem);
String[] content = lorem.split(".");
inboxStyle.setBigContentTitle("This is a big title");
for (String line : content) {
inboxStyle.addLine(line);
}
// Building the notification
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.ic_launcher)
"Android Application Development Company India" www.letsnurture.com
.setContentTitle("Expandable notification")
.setContentText("An example of an expandable notification")
.setStyle(inboxStyle);
mNotificationManager.notify(11, nBuilder.build());
} else {
Toast.makeText(context, "Can't show", Toast.LENGTH_LONG).show();
}
Create Progress in a Notification
To display a determinate progress bar, add the bar to your notification by
calling setProgress() setProgress(max, progress, false) and then issue the
notification. As your operation proceeds, increment progress, and update the
notification. At the end of the operation, progress should equal max. A common
way to call setProgress() is to set max to 100 and then increment progress as a
"percent complete" value for the operation.
You can either leave the progress bar showing when the operation is done, or
remove it. In either case, remember to update the notification text to show that
the operation is complete. to remove the progress bar, call setProgress()
setProgress(0, 0, false).
// used to update the progress notification
final int progresID = new Random().nextInt(1000);
// building the notification
final NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Progres notification")
.setContentText("Now waiting")
.setTicker("Progress notification created")
.setUsesChronometer(true).setProgress(100, 0, true);
AsyncTask<Integer, Integer, Integer> downloadTask = new AsyncTask<Integer, Integer, Integer>() {
@Override
"Android Application Development Company India" www.letsnurture.com
protected void onPreExecute() {
super.onPreExecute();
mNotificationManager.notify(progresID, nBuilder.build());
}
@Override
protected Integer doInBackground(Integer... params) {
try {
// Sleeps 2 seconds to show the undeterminated progress
Thread.sleep(5000);
// update the progress
for (int i = 0; i < 101; i += 5) {
nBuilder.setContentTitle("Progress running...")
.setContentText("Now running...")
.setProgress(100, i, false)
.setSmallIcon(R.drawable.ic_launcher)
.setContentInfo(i + " %");
// use the same id for update instead created another
// one
mNotificationManager.notify(progresID, nBuilder.build());
Thread.sleep(500);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
"Android Application Development Company India" www.letsnurture.com
nBuilder.setContentText("Progress finished :D")
.setContentTitle("Progress finished !!")
.setTicker("Progress finished !!!")
.setSmallIcon(R.drawable.ic_launcher)
.setUsesChronometer(false);
mNotificationManager.notify(progresID, nBuilder.build());
}
};
// Executes the progress task
downloadTask.execute();
Now add Buttons to Notification Like Alarma Notification have two button one
foe snoose and another for stop.
Follow bellow steps to add buttons.
Step 1: simply create simple notification as above discription.
Step 2: use this method to add action when creating notification
NotificationCompat.Builder addAction (int icon, CharSequence title,
PendingIntent intent);
Actions are typically displayed by the system as a button adjacent to the
notification content.
Note: Action buttons won't appear on platforms prior to Android 4.1. Action
buttons depend on expanded notifications, which are only available in Android
4.1 and later.
See bellow example for add buttons.
"Android Application Development Company India" www.letsnurture.com
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// Prepare intent which is triggered if the notification button is
// pressed
Intent intent = new Intent(context, TestActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0,
intent, 0);
// Building the notification
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Button notification")
.setContentText("Expand to show the buttons...")
.setTicker("Showing button notification")
// action added here with pending intent.
.addAction(R.drawable.ic_launcher, "Accept", pIntent)
.addAction(R.drawable.ic_launcher, "Cancel", pIntent);
mNotificationManager.notify(1001, nBuilder.build());
} else {
Toast.makeText(context, "You need a higher version",
Toast.LENGTH_LONG).show();
}
Link of Source Code

Weitere ähnliche Inhalte

Was ist angesagt?

Londroid Android Home Screen Widgets
Londroid Android Home Screen WidgetsLondroid Android Home Screen Widgets
Londroid Android Home Screen Widgets
Richard Hyndman
 
Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
Ahsanul Karim
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
Utkarsh Mankad
 

Was ist angesagt? (16)

Londroid Android Home Screen Widgets
Londroid Android Home Screen WidgetsLondroid Android Home Screen Widgets
Londroid Android Home Screen Widgets
 
Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
 
Android Workshop: Day 1 Part 3
Android Workshop: Day 1 Part 3Android Workshop: Day 1 Part 3
Android Workshop: Day 1 Part 3
 
Marakana Android User Interface
Marakana Android User InterfaceMarakana Android User Interface
Marakana Android User Interface
 
Android Tutorial
Android TutorialAndroid Tutorial
Android Tutorial
 
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on AndroidMobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
Mobile 2.0 Open Ideas WorkShop: Building Social Media Enabled Apps on Android
 
Android session 3
Android session 3Android session 3
Android session 3
 
Tang doanh thu quang cao di dong
Tang doanh thu quang cao di dongTang doanh thu quang cao di dong
Tang doanh thu quang cao di dong
 
Android session 2
Android session 2Android session 2
Android session 2
 
Android session 1
Android session 1Android session 1
Android session 1
 
Activity
ActivityActivity
Activity
 
Android
AndroidAndroid
Android
 
Unit i informatica en ingles
Unit i informatica en inglesUnit i informatica en ingles
Unit i informatica en ingles
 
Android intents, notification and broadcast recievers
Android intents, notification and broadcast recieversAndroid intents, notification and broadcast recievers
Android intents, notification and broadcast recievers
 
Lab1-android
Lab1-androidLab1-android
Lab1-android
 
Android developer interview questions with answers pdf
Android developer interview questions with answers pdfAndroid developer interview questions with answers pdf
Android developer interview questions with answers pdf
 

Andere mochten auch

รอยธรรมคำสอนพระเถระ 2
รอยธรรมคำสอนพระเถระ  2รอยธรรมคำสอนพระเถระ  2
รอยธรรมคำสอนพระเถระ 2
Na Tak
 
10 amazing routines using the dynamic coins gimmick
10 amazing routines using the dynamic coins gimmick10 amazing routines using the dynamic coins gimmick
10 amazing routines using the dynamic coins gimmick
Rafael Ferreira
 
Part of the sentences. Basic Grammar
Part of the sentences. Basic GrammarPart of the sentences. Basic Grammar
Part of the sentences. Basic Grammar
Liriett Herrera
 
структура сказки для 5 класса
структура сказки для 5 классаструктура сказки для 5 класса
структура сказки для 5 класса
kryljanauki
 
กาแฟแก้วหนึ่ง บนฝาผนัง
กาแฟแก้วหนึ่ง บนฝาผนังกาแฟแก้วหนึ่ง บนฝาผนัง
กาแฟแก้วหนึ่ง บนฝาผนัง
Na Tak
 
нормы построения предложений с до
нормы построения предложений с донормы построения предложений с до
нормы построения предложений с до
kryljanauki
 
для зачета по теме п и д
для зачета по теме п и ддля зачета по теме п и д
для зачета по теме п и д
kryljanauki
 
Ohionetegovojfswebinar
OhionetegovojfswebinarOhionetegovojfswebinar
Ohionetegovojfswebinar
Shelly Miller
 
โลกสอนฉัน
โลกสอนฉันโลกสอนฉัน
โลกสอนฉัน
Na Tak
 

Andere mochten auch (20)

Profile orang tua
Profile orang tuaProfile orang tua
Profile orang tua
 
รอยธรรมคำสอนพระเถระ 2
รอยธรรมคำสอนพระเถระ  2รอยธรรมคำสอนพระเถระ  2
รอยธรรมคำสอนพระเถระ 2
 
10 amazing routines using the dynamic coins gimmick
10 amazing routines using the dynamic coins gimmick10 amazing routines using the dynamic coins gimmick
10 amazing routines using the dynamic coins gimmick
 
Setup CSV Based Pricing in Magento
Setup CSV Based Pricing in Magento   Setup CSV Based Pricing in Magento
Setup CSV Based Pricing in Magento
 
Part of the sentences. Basic Grammar
Part of the sentences. Basic GrammarPart of the sentences. Basic Grammar
Part of the sentences. Basic Grammar
 
структура сказки для 5 класса
структура сказки для 5 классаструктура сказки для 5 класса
структура сказки для 5 класса
 
กาแฟแก้วหนึ่ง บนฝาผนัง
กาแฟแก้วหนึ่ง บนฝาผนังกาแฟแก้วหนึ่ง บนฝาผนัง
กาแฟแก้วหนึ่ง บนฝาผนัง
 
нормы построения предложений с до
нормы построения предложений с донормы построения предложений с до
нормы построения предложений с до
 
Parts of the plants1
Parts of the plants1Parts of the plants1
Parts of the plants1
 
для зачета по теме п и д
для зачета по теме п и ддля зачета по теме п и д
для зачета по теме п и д
 
Master trening startup_shevchuk 2015 v1.1
Master trening startup_shevchuk 2015 v1.1Master trening startup_shevchuk 2015 v1.1
Master trening startup_shevchuk 2015 v1.1
 
3. .xiaofei li 1
3. .xiaofei li 13. .xiaofei li 1
3. .xiaofei li 1
 
Улицы и площади
Улицы и площадиУлицы и площади
Улицы и площади
 
Sant jordi
Sant jordiSant jordi
Sant jordi
 
Ohionetegovojfswebinar
OhionetegovojfswebinarOhionetegovojfswebinar
Ohionetegovojfswebinar
 
Rent a parent
Rent a parentRent a parent
Rent a parent
 
Holes (themes)
Holes (themes)Holes (themes)
Holes (themes)
 
Смотр войск на Дворцовой площади
Смотр войск на Дворцовой площадиСмотр войск на Дворцовой площади
Смотр войск на Дворцовой площади
 
Introduction to Advanced Product Options
 Introduction to Advanced Product Options  Introduction to Advanced Product Options
Introduction to Advanced Product Options
 
โลกสอนฉัน
โลกสอนฉันโลกสอนฉัน
โลกสอนฉัน
 

Ähnlich wie Local Notification Tutorial

How to create android push notifications with custom view
How to create android push notifications with custom viewHow to create android push notifications with custom view
How to create android push notifications with custom view
PushApps - Content Recommendation in Push Notifications
 

Ähnlich wie Local Notification Tutorial (20)

Notification android
Notification androidNotification android
Notification android
 
Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...Implementation of Push Notification in React Native Android app using Firebas...
Implementation of Push Notification in React Native Android app using Firebas...
 
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 Wearables ii
Android Wearables iiAndroid Wearables ii
Android Wearables ii
 
Exercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone callExercises broadcast receiver,incoming phone call
Exercises broadcast receiver,incoming phone call
 
Getting Ready For Android Wear
Getting Ready For Android WearGetting Ready For Android Wear
Getting Ready For Android Wear
 
Titanium Appcelerator - Beginners
Titanium Appcelerator - BeginnersTitanium Appcelerator - Beginners
Titanium Appcelerator - Beginners
 
Android wear (coding)
Android wear (coding)Android wear (coding)
Android wear (coding)
 
How to create android push notifications with custom view
How to create android push notifications with custom viewHow to create android push notifications with custom view
How to create android push notifications with custom view
 
Basic Intro to android(Will be updating later)
Basic Intro to android(Will be updating later)Basic Intro to android(Will be updating later)
Basic Intro to android(Will be updating later)
 
Introduction to Android Wear
Introduction to Android WearIntroduction to Android Wear
Introduction to Android Wear
 
Developing for android wear
Developing for android wearDeveloping for android wear
Developing for android wear
 
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...
 
GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...
GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...
GDG GeorgeTown Devfest 2014 Presentation: Android Wear: A Developer's Perspec...
 
Android Wear Development
Android Wear DevelopmentAndroid Wear Development
Android Wear Development
 
Notifications
NotificationsNotifications
Notifications
 
Keynote + Next Gen UIs.pptx
Keynote + Next Gen UIs.pptxKeynote + Next Gen UIs.pptx
Keynote + Next Gen UIs.pptx
 
Ios - Introduction to platform & SDK
Ios - Introduction to platform & SDKIos - Introduction to platform & SDK
Ios - Introduction to platform & SDK
 
Android action bar and notifications-chapter16
Android action bar and notifications-chapter16Android action bar and notifications-chapter16
Android action bar and notifications-chapter16
 
Cloud Messaging Flutter
Cloud Messaging FlutterCloud Messaging Flutter
Cloud Messaging Flutter
 

Mehr von Ketan Raval

Android notifications
Android notificationsAndroid notifications
Android notifications
Ketan Raval
 

Mehr von Ketan Raval (20)

Amazon Alexa Auto Software Development Kit (SDK)
Amazon Alexa Auto Software Development Kit (SDK)Amazon Alexa Auto Software Development Kit (SDK)
Amazon Alexa Auto Software Development Kit (SDK)
 
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
Proximity Marketing Solutions enhancing Businesses leveraging iBeacon SDK Int...
 
Keynote 2016
Keynote 2016Keynote 2016
Keynote 2016
 
Zero ui future is here
Zero ui   future is hereZero ui   future is here
Zero ui future is here
 
Android n and beyond
Android n and beyondAndroid n and beyond
Android n and beyond
 
IoT and Future of Connected world
IoT and Future of Connected worldIoT and Future of Connected world
IoT and Future of Connected world
 
#Instagram API Get visibility you always wanted
#Instagram API   Get visibility you always wanted#Instagram API   Get visibility you always wanted
#Instagram API Get visibility you always wanted
 
Keynote - Devfest 2015 organized by GDG Ahmedabad
Keynote - Devfest 2015 organized by GDG AhmedabadKeynote - Devfest 2015 organized by GDG Ahmedabad
Keynote - Devfest 2015 organized by GDG Ahmedabad
 
Android notifications
Android notificationsAndroid notifications
Android notifications
 
How to make your Mobile App HIPPA Compliant
How to make your Mobile App HIPPA CompliantHow to make your Mobile App HIPPA Compliant
How to make your Mobile App HIPPA Compliant
 
3 d touch a true game changer
3 d touch a true game changer3 d touch a true game changer
3 d touch a true game changer
 
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel EconomyOBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
OBD Mobile App - Fault Codes, Driving Behaviour and Fuel Economy
 
Vehicle to vehicle communication using gps
Vehicle to vehicle communication using gpsVehicle to vehicle communication using gps
Vehicle to vehicle communication using gps
 
Obd how to guide
Obd how to guideObd how to guide
Obd how to guide
 
Garmin api integration
Garmin api integrationGarmin api integration
Garmin api integration
 
Beacon The Google Way
Beacon The Google WayBeacon The Google Way
Beacon The Google Way
 
Edge detection iOS application
Edge detection iOS applicationEdge detection iOS application
Edge detection iOS application
 
Google calendar integration in iOS app
Google calendar integration in iOS appGoogle calendar integration in iOS app
Google calendar integration in iOS app
 
Big data cloudcomputing
Big data cloudcomputingBig data cloudcomputing
Big data cloudcomputing
 
All about Apple Watchkit
All about Apple WatchkitAll about Apple Watchkit
All about Apple Watchkit
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Local Notification Tutorial

  • 1. "Android Application Development Company India" www.letsnurture.com Local Notification Tutorial
  • 2. "Android Application Development Company India" www.letsnurture.com Android Notifications Android allows to put notification into the titlebar of your application. The user can expand the notification bar and by selecting the notification the user can trigger another activity. Here we have used NotificationCompat because on older platform versions that don't offer expanded notifications, methods that depend on expanded notifications have no effect. For example, action buttons won't appear on platforms prior to Android 4.1. Action buttons depend on expanded notifications, which are only available in Android 4.1 and later. So provide support support lib v4 follow below step to create Notification with different style. Step 1: Create Notification Builder Create Notification Builder using NotificationCompat.Builder.build(). NotificationCompat.Builder. Used for set various Notification Properties like its small and large icons,title priority ... // Building the notification NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); Step 2 : Setting Notification Properties Once you have Builder object, you can set its Notification properties using Builder object as per your requirement. But this is mandatory to set at least following: A small icon, set by setSmallIcon() A title, set by setContentTitle() Detail text, set by setContentText() NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( context).setSmallIcon(R.drawable.ic_launcher) .setContentTitle("simple notification")
  • 3. "Android Application Development Company India" www.letsnurture.com .setContentText("the text of the simple notification") Step 3 - Attach Action to Notification This is an optional part and required if you want to attach an action with the notification. An action allows users to redirecte from the notification to an Activity in application, where they can look at one or more events or do further work. The action can be achived by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method of NotificationCompat.Builder. For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent(). // Pending intent to the notification manager PendingIntent resultPending = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); // Building the notification NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( context).setSmallIcon(R.drawable.ic_launcher) .setContentTitle("simple notification") .setContentText("the text of the simple notification") .setContentIntent(resultPending);// attach action here. Step 4 : Issue the notifacation You pass the Notification object to the system by calling NotificationManager.notify() to send your notification. Make sure you call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a newNotification object. // mId allows you to update the notification later on. NotificationManager mNotificationManager.notify(10, mBuilder.build()); This Method post a notification to be shown in the status bar. If a notification with the same id has already been posted by application and has not yet been canceled, it will be replaced by the updated information.
  • 4. "Android Application Development Company India" www.letsnurture.com Set Notification Priority You can set the priority of a notification. The priority acts as a hint to the device UI about how the notification should be displayed. To set a notification's priority, callNotificationCompat.Builder.setPriority() and pass in one of the NotificationCompat priority constants. There are five priority levels, ranging from PRIORITY_MIN (-2) to PRIORITY_MAX (2); if not set, the priority defaults to PRIORITY_DEFAULT (0). Here we have created differet kind of Notification. Create a big view style to a notification To Create Notification in a big view when it's expanded, first create a NotificationCompat.Builder object with the normal view. Next, call Builder.setStyle() with a big view style object as its argument. Note: expanded notifications are not available on platforms prior to Android 4.1.how to handle notifications for Android 4.1 and for earlier platforms, read the section Handling compatibility. if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // Building the expandable content NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); String lorem = context.getResources() .getString(R.string.long_lorem); String[] content = lorem.split("."); inboxStyle.setBigContentTitle("This is a big title"); for (String line : content) { inboxStyle.addLine(line); } // Building the notification NotificationCompat.Builder nBuilder = new NotificationCompat.Builder( context).setSmallIcon(R.drawable.ic_launcher)
  • 5. "Android Application Development Company India" www.letsnurture.com .setContentTitle("Expandable notification") .setContentText("An example of an expandable notification") .setStyle(inboxStyle); mNotificationManager.notify(11, nBuilder.build()); } else { Toast.makeText(context, "Can't show", Toast.LENGTH_LONG).show(); } Create Progress in a Notification To display a determinate progress bar, add the bar to your notification by calling setProgress() setProgress(max, progress, false) and then issue the notification. As your operation proceeds, increment progress, and update the notification. At the end of the operation, progress should equal max. A common way to call setProgress() is to set max to 100 and then increment progress as a "percent complete" value for the operation. You can either leave the progress bar showing when the operation is done, or remove it. In either case, remember to update the notification text to show that the operation is complete. to remove the progress bar, call setProgress() setProgress(0, 0, false). // used to update the progress notification final int progresID = new Random().nextInt(1000); // building the notification final NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("Progres notification") .setContentText("Now waiting") .setTicker("Progress notification created") .setUsesChronometer(true).setProgress(100, 0, true); AsyncTask<Integer, Integer, Integer> downloadTask = new AsyncTask<Integer, Integer, Integer>() { @Override
  • 6. "Android Application Development Company India" www.letsnurture.com protected void onPreExecute() { super.onPreExecute(); mNotificationManager.notify(progresID, nBuilder.build()); } @Override protected Integer doInBackground(Integer... params) { try { // Sleeps 2 seconds to show the undeterminated progress Thread.sleep(5000); // update the progress for (int i = 0; i < 101; i += 5) { nBuilder.setContentTitle("Progress running...") .setContentText("Now running...") .setProgress(100, i, false) .setSmallIcon(R.drawable.ic_launcher) .setContentInfo(i + " %"); // use the same id for update instead created another // one mNotificationManager.notify(progresID, nBuilder.build()); Thread.sleep(500); } } catch (InterruptedException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Integer integer) { super.onPostExecute(integer);
  • 7. "Android Application Development Company India" www.letsnurture.com nBuilder.setContentText("Progress finished :D") .setContentTitle("Progress finished !!") .setTicker("Progress finished !!!") .setSmallIcon(R.drawable.ic_launcher) .setUsesChronometer(false); mNotificationManager.notify(progresID, nBuilder.build()); } }; // Executes the progress task downloadTask.execute(); Now add Buttons to Notification Like Alarma Notification have two button one foe snoose and another for stop. Follow bellow steps to add buttons. Step 1: simply create simple notification as above discription. Step 2: use this method to add action when creating notification NotificationCompat.Builder addAction (int icon, CharSequence title, PendingIntent intent); Actions are typically displayed by the system as a button adjacent to the notification content. Note: Action buttons won't appear on platforms prior to Android 4.1. Action buttons depend on expanded notifications, which are only available in Android 4.1 and later. See bellow example for add buttons.
  • 8. "Android Application Development Company India" www.letsnurture.com if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // Prepare intent which is triggered if the notification button is // pressed Intent intent = new Intent(context, TestActivity.class); PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0); // Building the notification NotificationCompat.Builder nBuilder = new NotificationCompat.Builder( context).setSmallIcon(R.drawable.ic_launcher) .setContentTitle("Button notification") .setContentText("Expand to show the buttons...") .setTicker("Showing button notification") // action added here with pending intent. .addAction(R.drawable.ic_launcher, "Accept", pIntent) .addAction(R.drawable.ic_launcher, "Cancel", pIntent); mNotificationManager.notify(1001, nBuilder.build()); } else { Toast.makeText(context, "You need a higher version", Toast.LENGTH_LONG).show(); } Link of Source Code