Saturday, 10 December 2016

Creating interfaces between Java script code and Client side Android code

When developing a web application that's designed specifically for the WebView in your Android application, you can create interfaces between your JavaScript code and client-side Android code. For example, your JavaScript code can call a method in your Android code to display a Dialog, instead of using JavaScript's alert() function.

Code below:
browser.addJavascriptInterface(new WebAppInterface(WebViewActivty.this), "Android");

Webview Public methods

addJavascriptInterface

void addJavascriptInterface (Object object, String name)
Injects the supplied Java object into this WebView. The object is injected into the JavaScript context of the main frame, using the supplied name. This allows the Java object's methods to be accessed from JavaScript. For applications targeted to API level JELLY_BEAN_MR1 and above, only public methods that are annotated with JavascriptInterface can be accessed from JavaScript. For applications targeted to API level JELLY_BEAN or below, all public methods (including the inherited ones) can be accessed, see the important security note below for implications.

IMPORTANT:

This method can be used to allow JavaScript to control the host application. This is a powerful feature, but also presents a security risk for apps targeting JELLY_BEAN or earlier. Apps that target a version later than JELLY_BEAN are still vulnerable if the app runs on a device running Android earlier than 4.2. The most secure way to use this method is to target JELLY_BEAN_MR1 and to ensure the method is called only when running on Android 4.2 or later. With these older versions, JavaScript could use reflection to access an injected object's public fields. Use of this method in a WebView containing untrusted content could allow an attacker to manipulate the host application in unintended ways, executing Java code with the permissions of the host application. Use extreme care when using this method in a WebView which could contain untrusted content.

JavaScript interacts with Java object on a private, background thread of this WebView. Care is therefore required to maintain thread safety.
The Java object's fields are not accessible.

For applications targeted to API level LOLLIPOP and above, methods of injected Java objects are enumerable from JavaScript.

<html>
<head>
<style>
body{
background-color: #5F9EA0;
color:#fff;
}
input{
background-color: #B0C4DE;
width: 300px;
padding:10px;
color: #000;
}
div#content{
padding:20px;
background-color: #B0C4DE;
color: #000;
}
</style>
</head>
<body>
<script src="./index.js"></script>
<center>
<h3>Binding JavaScript code to Android code</h3>
<div id="content">
When developing a web application that's designed specifically for the WebView in your Android application, you can create interfaces between your JavaScript code and client-side Android code. For example, your JavaScript code can call a method in your Android code to display a Dialog, instead of using JavaScript's alert() function.
</div>
<div style="font-weight:bold">
    <br/>Calling Android Method from Java Script:
</div>
<div><br/>




<input type="button" value="Make Toast" onClick="showAndroidToast('Toast made by Javascript :)')" /><br/>
<input type="button" value="Trigger Dialog" onClick="showAndroidDialog('This dialog is triggered by Javascript :)')" /><br/>
<input type="button" value="Take me to Next Screen" onClick="moveToScreenTwo()" />
</div>
</center>

</body>
</html>


To get Code Click Here









Monday, 30 May 2016

Android Interview Questions and Answers -Part 2

1)Difference between listview and recyclerview 

i) ViewHolder Pattern

In a ListView, it was recommended to use the ViewHolder pattern but it was never a compulsion. In case of RecyclerView, this is mandatory using the RecyclerView.ViewHolder class. This is one of the major differences between the ListView and the RecyclerView.

It makes things a bit more complex in RecyclerView but a lot of problems that we faced in the ListView are solved efficiently.

Reuse cells while scrolling up/down - this is possible with implementing View Holder in the listView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

ii) LayoutManager

This is another massive enhancement brought to the RecyclerView. In a ListView, the only type of view available is the vertical ListView. There is no official way to even implement a horizontal ListView.

Now using a RecyclerView, we can have a

i) LinearLayoutManager - which supports both vertical and horizontal lists,

ii) StaggeredLayoutManager - which supports Pinterest like staggered lists,

iii) GridLayoutManager - which supports displaying grids as seen in Gallery apps.

And the best thing is that we can do all these dynamically as we want.

iii) Item Animator

ListViews are lacking in support of good animations, but the RecyclerView brings a whole new dimension to it. Using the RecyclerView.ItemAnimator class, animating the views becomes so much easy and intuitive.

iv) Item Decoration

In case of ListViews, dynamically decorating items like adding borders or dividers was never easy. But in case of RecyclerView, the RecyclerView.ItemDecorator class gives huge control to the developers but makes things a bit more time consuming and complex.

v) OnItemTouchListener

Intercepting item clicks on a ListView was simple, thanks to its AdapterView.OnItemClickListener interface. But the RecyclerView gives much more power and control to its developers by the RecyclerView.OnItemTouchListener but it complicates things a bit for the developer.

In simple words, the RecyclerView is much more customizable than the ListView and gives a lot of control and power to its developers.


What is final in Java? 

Final in java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase performance of Java application.

What is final keyword in Java?

Final keyword, final variable, final method and class in java exampleFinal is a keyword or reserved word in java and can be applied to member variables, methods, class and local variables in Java. Once you make a reference final you are not allowed to change that reference and compiler will verify this and raise compilation error if you try to re-initialized final variables in java.

What is final variable in Java?
Any variable either member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant. Here is an example of final variable in Java

public static final String LOAN = "loan";
LOAN = new String("loan") //invalid compilation error

Final variables are by default read-only.


What is final method in Java
Final keyword in java can also be applied to methods. A java method with final keyword is called final method and it can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time. Here is an example of final method in Java:

class PersonalLoan{
 public final String getName(){
     return "personal loan";
 }
}
class CheapPersonalLoan extends PersonalLoan{
    @Override
    public final String getName(){
        return "cheap personal loan"; //compilation error: overridden method is final
    }
}

What is final Class in Java

Java class with final modifier is called final class in Java. Final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes. Here is an example of final class in java

final class PersonalLoan{

}

class CheapPersonalLoan extends PersonalLoan{  //compilation error: cannot inherit from final class

}

Benefits of final keyword in Java

Here are few benefits or advantage of using final keyword in Java:

1. Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.

2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.

3. Final keyword allows JVM to optimized method, variable or class.


Final and Immutable Class in Java

Final keyword helps to write immutable class. Immutable classes are the one which can not be modified once it gets created and String is primary example of immutable and final class which I have discussed in detail on Why String is final or immutable in Java. Immutable classes offer several benefits one of them is that they are effectively read-only and can be safely shared in between multiple threads without any synchronization overhead. You can not make a class immutable without making it final and hence final keyword is required to make a class immutable in java.

Example of Final in Java

Java has several system classes in JDK which are final, some example of final classes are String, Integer, Double and other wrapper classes. You can also use final keyword to make your code better whenever it required. See relevant section of java final tutorial for example of final variable, final method and final class in Java.

Important points on final in Java

1. Final keyword can be applied to member variable, local variable, method or class in Java.
2. Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.

3. You can not reassign value to final variable in Java.

4. Local final variable must be initializing during declaration.

5. Only final variable is accessible inside anonymous class in Java.

6. Final method can not be overridden in Java.

7. Final class can not be inheritable in Java.

8. Final is different than finally keyword which is used on Exception handling in Java.

9. Final should not be confused with finalize() method which is declared in object class and called before an object is garbage collected by JVM.

10. All variable declared inside java interface are implicitly final.

11. Final and abstract are two opposite keyword and a final class can not be abstract in java.

12. Final methods are bonded during compile time also called static binding.

13. Final variables which is not initialized during declaration are called blank final variable and must be initialized on all constructor either explicitly or by calling this(). Failure to do so compiler will complain as "final variable (name) might not be initialized".

14. Making a class, method or variable final in Java helps to improve performance because JVM gets an opportunity to make assumption and optimization.

15. As per Java code convention final variables are treated as constant and written in all Caps e.g.

private final int COUNT=10;

16. Making a collection reference variable final means only reference can not be changed but you can add, remove or change object inside collection. For example:

private final List loans = new ArrayList();
loans.add(“home loan”);  //valid
loans.add("personal loan"); //valid
loans = new Vector();  //not valid

That’s all on final in Java. We have seen what final variable, final method is and final class in Java and what does those mean. In Summary whenever possible start using final in java it would result in better and faster code.

Difference between Hashtable and HashMap in Java

Hashtable vs HashMap in Java
Hashtable and HashMap are two hash based collection in Java and used to store objects as key value pair. Despite being hash based and similar in functionality there are a significant difference between Hashtable and HashMap and without understanding those difference if you use Hashtable in place of HashMap than you may run into series of subtle programs which is hard to find and debug.Unlike Difference between ArrayList and HashMap,  Difference between Hashtable and HashMap are more subtle because both are similar kind of collection. Before seeing difference between HashMap and Hashtable let's see some common things between HashMap and Hashtable in Java.



Similarities between Hashtable and HashMap in Java
There are lot of similar things between Hashtable and HashMap in Java which is good to know and these also helps to find exactly what is different between HashMap and Hashtable in Java:

1) Both Hashtable and HashMap implements java.util.Map interface.
2) Hashtable and HashMap both are a hash based collection and works on the principle of hashing.
3) Hashtable and HashMap both provide constant time performance for put and get method if objects are distributed uniformly across bucket.
4) From JDK 4 both Hashtable and HashMap are part of Java collection framework.

Difference between Hashtable and HashMap in Java
What is Difference between HashMap and Hashtable in Java CollectionDespite being so similar there are some differences between Hashtable and HashMap in Java which separates them completely, let's have a look :
1) First and most significantly different between Hashtable and HashMap are that HashMap is not thread-safe  while Hashtable is a thread-safe collection.

2) The second important difference between Hashtable and HashMap is performance since HashMap is not synchronized it perform better than Hashtable.

3) The third difference on Hashtable vs HashMap is that Hashtable is obsolete class and you should be using ConcurrentHashMap in place of Hashtable in Java.

These were some important difference on Hashtable and HashMap in Java. If you know any other difference which is not included here then feels free to add them in the comment section. Remember this is an important question on Java interview and good to prepare it well.

AIDL

Each Android app run in it’s own process. So one application can’t directly access another app’s memory space. If you want to access some data from one application to another application, then we need to use  inter process communication (IPC) like other platforms. So in Android IPC is otherwise known as AIDL. For this purpose Android provides a technique called Android Interface Definition Language (AIDL). It is a lightweight implementation of IPC just like C/C++ languages.

So to communicate between process or you say between applications, we need to implement AIDL in our Android application. In other words you can say the AIDL technique is a light weighted client server architecture in form of a service, which helps multiple applications to communicate between them self.  To do so we need the below steps.

1. AIDL interface- Define a AIDL interface which will be the interface between your applications.
2. Implement the the remote service- Remote service holds your data/method to expose to other applications for accessing data.

3. Expose the remote service to other local clients- The data/method we need to share with other applications needs to be expose so that other application can access and share data from the remote service.


Java - How to use Singleton Class ?
The Singleton's purpose is to control object creation, limiting the number of obejcts to one only. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources.

Example 
// File Name: Singleton.java
public class Singleton {

   private static Singleton singleton = new Singleton( );
   
   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }
   
   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}
Here is the main program file where we will create singleton object:



// File Name: SingletonDemo.java
public class SingletonDemo {
   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}

Difference between Singleton Pattern vs Static Class in Java

 similarities 
both can be used without creating object
both provide only one instance

1)Why you use Singleton instead of Static Methods?
2)Can you replace Singleton with static class?
3)what are differences between Singleton pattern and static in Java?

static class is a Java class, which only contains static methods

While Singleton classes are those, which has only one instance during application life cycle 

1) Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.

2) One more difference between Singleton and static is, ability to override. Since static methods in Java cannot be overridden, they leads to inflexibility. On the other hand, you can override methods defined in Singleton class by extending it.

3) Static classes are hard to mock and consequently hard to test than Singletons, which are pretty easy to mock and thus easy to test. It’s easier to write JUnit test for Singleton than static classes, because you can pass mock object whenever Singleton is expected, e.g. into constructor or as method arguments.

4) If your requirements needs to maintain state than Singleton pattern is better choice than static class, because
maintaining  state in later case is nightmare and leads to subtle bugs.

5) Singleton classes can be lazy loaded if its an heavy object, but static class doesn't have such advantages and always eagerly loaded.

6) Many Dependency Injection framework manages Singleton quite well e.g. Spring, which makes using them very easy.

These are some differences between static class and singleton pattern, this will help to decide between two, which situation arises. In next section we will when to choose Singleton pattern over static class in Java.


Main advantage of Singleton over static is that former is more object oriented than later. With Singleton, you can use Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. If we talk about java.lang.Runtime, which is a Singleton in Java, call to getRuntime() method return different implementations based on different JVM, but guarantees only one instance per JVM, had java.lang.Runtime an static class, it’s not possible to return different implementation for different JVM.

That’s all on difference between Singleton and static class in Java. When you need a class with full OO capability , chose Singleton, while if you just need to store bunch of static methods together, than use static class.

What is Singleton class? Have you used Singleton before?

Singleton is a class which has only one instance in whole application and provides a getInstance() method to access the singleton instance. There are many classes in JDK which is implemented using Singleton pattern like java.lang.Runtime which provides getRuntime() method to get access of it and used to get free memory and total memory in Java.


Which classes are candidates of Singleton? Which kind of class do you make Singleton in Java?

Here they check whether candidate has enough experience on usage of singleton or not. Does he is familiar of advantage/disadvantage or alternatives available for singleton in Java or not.

Answer : Any class which you want to be available to whole application and whole only one instance is viable is candidate of becoming Singleton. One example of this is Runtime class , since on whole java application only one runtime environment can be possible making Runtime Singleton is right decision. Another example is a utility classes like Popup in GUI application, if you want to show popup with message you can have one PopUp class on whole GUI application and anytime just get its instance, and call show() with message.


Can you write code for getInstance() method of a Singleton class in Java?

Most of the java programmer fail here if they have mugged up the singleton code because you can ask lots of follow-up question based upon the code they have written. I have seen many programmer write Singleton getInstance() method with double checked locking but they are not really familiar with the caveat associated with double checking of singleton prior to Java 5.

Answer : Until asked don’t write code using double checked locking as it is more complex and chances of errors are more but if you have deep knowledge of double checked locking, volatile variable and lazy loading than this is your chance to shine. I have shared code examples of writing singleton classes using enum, using static factory and with double checked locking in my recent post Why Enum Singletons are better in Java, please see there.

Singleton design pattern Interview Questions in Java


Is it better to make whole getInstance() method synchronized or just critical section is enough? Which one you will prefer?

This is really nice question and I mostly asked to just quickly check whether candidate is aware of performance trade off of unnecessary locking or not. Since locking only make sense when we need to create instance and rest of the time its just read only access so locking of critical section is always better option. read more about synchronization on How Synchronization works in Java
Answer : This is again related to double checked locking pattern, well synchronization is costly and when you apply this on whole method than call to getInstance() will be synchronized and contented. Since synchronization is only needed during initialization on singleton instance, to prevent creating another instance of Singleton, It’s better to only synchronize critical section and not whole method. Singleton pattern is also closely related to factory design pattern where getInstance() serves as static factory method.



What is lazy and early loading of Singleton and how will you implement it?

This is another great Singleton interview question in terms of understanding of concept of loading and cost associated with class loading in Java. Many of which I have interviewed not really familiar with this but its good to know concept.

Answer : As there are many ways to implement Singleton like using double checked locking or Singleton class with static final instance initialized during class loading. Former is called lazy loading because Singleton instance is created only when client calls getInstance() method while later is called early loading because Singleton instance is created when class is loaded into memory.



Give me some examples of Singleton pattern from Java Development Kit?

This is open question to all, please share which classes are Singleton in JDK. Answer to this question is java.lang.Runtime
Answer : There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:
Java.lang.Runtime with getRuntime() method 
Java.awt.Toolkit with getDefaultToolkit() 
Java.awt.Desktop with getDesktop() 



What is double checked locking in Singleton?

One of the most hyped question on Singleton pattern and really demands complete understanding to get it right because of Java Memory model caveat prior to Java 5. If a guy comes up with a solution of using volatile keyword with Singleton instance and explains it then it really shows it has in depth knowledge of Java memory model and he is constantly updating his Java knowledge.

Answer : Double checked locking is a technique to prevent creating another instance of Singleton when call to getInstance() method is made in multi-threading environment. In Double checked locking pattern as shown in below example, singleton instance is checked two times before initialization. See here to learn more about double-checked-locking in Java. 

public static Singleton getInstance(){
     if(_INSTANCE == null){
         synchronized(Singleton.class){
         //double checked locking - because second check of Singleton instance with lock
                if(_INSTANCE == null){
                    _INSTANCE = new Singleton();
                }
            }
         }
     return _INSTANCE;
}

Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.



How do you prevent for creating another instance of Singleton using clone() method?

This type of questions generally comes some time by asking how to break singleton or when Singleton is not Singleton in Java.

Answer : Preferred way is not to implement Cloneable interface as why should one wants to create clone() of Singleton and if you do just throw Exception from clone() method as “Can not create clone of Singleton class”.



How do you prevent for creating another instance of Singleton using reflection?

Open to all. In my opinion throwing exception from constructor is an option.
Answer: This is similar to previous interview question. Since constructor of Singleton class is supposed to be private it prevents creating instance of Singleton from outside but Reflection can access private fields and methods, which opens a threat of another instance. This can be avoided by throwing Exception from constructor as “Singleton already initialized”



How do you prevent for creating another instance of Singleton during serialization?

Another great question which requires knowledge of Serialization in Java and how to use it for persisting Singleton classes. This is open to you all but in my opinion use of readResolve() method can sort this out for you.
Answer: You can prevent this by using readResolve() method, since during serialization readObject() is used to create instance and it return new instance every time but by using readResolve you can replace it with original Singleton instance. I have shared code on how to do it in my post Enum as Singleton in Java. This is also one of the reason I have said that use Enum to create Singleton because serialization of enum is taken care by JVM and it provides guaranteed of that.


When is Singleton not a Singleton in Java?

There is a very good article present in Sun's Java site which discusses various scenarios when a Singleton is not really remains Singleton and multiple instance of Singleton is possible. 


Apart from these questions on Singleton pattern, some of my reader contribute few more questions, which I included here. Thank you guys for your contribution.


Why you should avoid the singleton anti-pattern at all and replace it with DI?

Answer : Singleton Dependency Injection: every class that needs access to a singleton gets the object through its constructors or with a DI-container.


Why Singleton is Anti pattern 

With more and more classes calling getInstance() the code gets more and more tightly coupled, monolithic, not testable and hard to change and hard to reuse because of not configurable, hidden dependencies. Also, there would be no need for this clumsy double checked locking if you call getInstance less often (i.e. once).


How many ways you can write Singleton Class in Java?

Answer : I know at least four ways to implement Singleton pattern in Java
Singleton by synchronizing getInstance() method
Singleton with public static final field initialized during class loading.
Singleton generated by static nested class, also referred as Singleton holder pattern.
From Java 5 on-wards using Enums


How to write thread-safe Singleton in Java?

Answer : Thread safe Singleton usually refers to write thread safe code which creates one and only one instance of Singleton if called by multiple thread at same time. There are many ways to achieve this like by using double checked locking technique as shown above and by using Enum or Singleton initialized by class loader.






Tuesday, 24 May 2016

Android Notification with different format

A notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.

Design Considerations
Notifications, as an important part of the Android user interface, have their own design guidelines. The material design changes introduced in Android 5.0 (API level 21) are of particular importance, and you should review the Material Design training for more information.

Creating a Notification
You specify the UI information and actions for a notification in a NotificationCompat.Builder object. To create the notification itself, you call NotificationCompat.Builder.build(), which returns a Notification object containing your specifications. To issue the notification, you pass the Notification object to the system by calling NotificationManager.notify().

Required notification contents
A Notification object must contain the following:

A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
Optional notification contents and settings
All other notification settings and contents are optional.

Notification actions
Although they're optional, you should add at least one action to your notification. An action allows users to go directly from the notification to an Activity in your application, where they can look at one or more events or do further work.

A notification can provide multiple actions. You should always define the action that's triggered when the user clicks the notification; usually this action opens an Activity in your application. You can also add buttons to the notification that perform additional actions such as snoozing an alarm or responding immediately to a text message; this feature is available as of Android 4.1. If you use additional action buttons, you must also make their functionality available in an Activity in your app; see the section Handling compatibility for more details.

Inside a Notification, the action itself is defined 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().

Starting an Activity when the user clicks the notification is the most common action scenario. You can also start an Activity when the user dismisses a notification. In Android 4.1 and later, you can start an Activity from an action button. To learn more, read the reference guide for NotificationCompat.Builder.

Notification priority
If you wish, 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, call NotificationCompat.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).

For information about setting an appropriate priority level, see "Correctly set and manage notification priority" in the Notifications Design guide.

Creating a simple notification
The following snippet illustrates a simple notification that specifies an activity to open when the user clicks the notification. Notice that the code creates a TaskStackBuilder object and uses it to create the PendingIntent for the action. This pattern is explained in more detail in the section Preserving Navigation when Starting an Activity:

NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);

// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
        );
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());

That's it. Your user has now been notified.

Applying an expanded layout to a notification
To have a notification appear in an expanded view, first create a NotificationCompat.Builder object with the normal view options you want. Next, call Builder.setStyle() with an expanded layout object as its argument.

Remember that expanded notifications are not available on platforms prior to Android 4.1. To learn how to handle notifications for Android 4.1 and for earlier platforms, read the section Handling compatibility.

For example, the following code snippet demonstrates how to alter the notification created in the previous snippet to use the expanded layout:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("Event tracker")
    .setContentText("Events received")
NotificationCompat.InboxStyle inboxStyle =
        new NotificationCompat.InboxStyle();
String[] events = new String[6];
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle("Event tracker details:");
...
// Moves events into the expanded layout
for (int i=0; i < events.length; i++) {

    inboxStyle.addLine(events[i]);
}
// Moves the expanded layout object into the notification object.
mBuilder.setStyle(inBoxStyle);
...
// Issue the notification here.

Handling compatibility
Not all notification features are available for a particular version, even though the methods to set them are in the support library class NotificationCompat.Builder. For example, action buttons, which depend on expanded notifications, only appear on Android 4.1 and higher, because expanded notifications themselves are only available on Android 4.1 and higher.

To ensure the best compatibility, create notifications with NotificationCompat and its subclasses, particularly NotificationCompat.Builder. In addition, follow this process when you implement a notification:

Provide all of the notification's functionality to all users, regardless of the version they're using. To do this, verify that all of the functionality is available from an Activity in your app. You may want to add a new Activity to do this.

For example, if you want to use addAction() to provide a control that stops and starts media playback, first implement this control in an Activity in your app.

Ensure that all users can get to the functionality in the Activity, by having it start when users click the notification. To do this, create a PendingIntent for the Activity. Call setContentIntent() to add the PendingIntent to the notification.

Now add the expanded notification features you want to use to the notification. Remember that any functionality you add also has to be available in the Activity that starts when users click the notification.

Managing Notifications
When you need to issue a notification multiple times for the same type of event, you should avoid making a completely new notification. Instead, you should consider updating a previous notification, either by changing some of its values or by adding to it, or both.

For example, Gmail notifies the user that new emails have arrived by increasing its count of unread messages and by adding a summary of each email to the notification. This is called "stacking" the notification; it's described in more detail in the Notifications Design guide.

Note: This Gmail feature requires the "inbox" expanded layout, which is part of the expanded notification feature.

The following section describes how to update notifications and also how to remove them.

Updating notifications
To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(). To update this notification once you've issued it, update or create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the same ID you used previously. If the previous notification is still visible, the system updates it from the contents of the Notification object. If the previous notification has been dismissed, a new notification is created instead.

The following snippet demonstrates a notification that is updated to reflect the number of events that have occurred. It stacks the notification, showing a summary:

mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
    .setContentTitle("New Message")
    .setContentText("You've received new messages.")
    .setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
    mNotifyBuilder.setContentText(currentText)
        .setNumber(++numMessages);
    // Because the ID remains unchanged, the existing notification is
    // updated.
    mNotificationManager.notify(
            notifyID,
            mNotifyBuilder.build());
...

Removing notifications
Notifications remain visible until one of the following happens:

The user dismisses the notification either individually or by using "Clear All" (if the notification can be cleared).
The user clicks the notification, and you called setAutoCancel() when you created the notification.
You call cancel() for a specific notification ID. This method also deletes ongoing notifications.
You call cancelAll(), which removes all of the notifications you previously issued.
Preserving Navigation when Starting an Activity
When you start an Activity from a notification, you must preserve the user's expected navigation experience. Clicking Back should take the user back through the application's normal work flow to the Home screen, and clicking Recents should show the Activity as a separate task. To preserve the navigation experience, you should start the Activity in a fresh task. How you set up the PendingIntent to give you a fresh task depends on the nature of the Activity you're starting. There are two general situations:

Regular activity:
You're starting an Activity that's part of the application's normal workflow. In this situation, set up the PendingIntent to start a fresh task, and provide the PendingIntent with a back stack that reproduces the application's normal Back behavior.
Notifications from the Gmail app demonstrate this. When you click a notification for a single email message, you see the message itself. Touching Back takes you backwards through Gmail to the Home screen, just as if you had entered Gmail from the Home screen rather than entering it from a notification.

This happens regardless of the application you were in when you touched the notification. For example, if you're in Gmail composing a message, and you click a notification for a single email, you go immediately to that email. Touching Back takes you to the inbox and then the Home screen, rather than taking you to the message you were composing.

Special activity
The user only sees this Activity if it's started from a notification. In a sense, the Activity extends the notification by providing information that would be hard to display in the notification itself. For this situation, set up the PendingIntent to start in a fresh task. There's no need to create a back stack, though, because the started Activity isn't part of the application's activity flow. Clicking Back will still take the user to the Home screen.
Setting up a regular activity PendingIntent
To set up a PendingIntent that starts a direct entry Activity, follow these steps:

Define your application's Activity hierarchy in the manifest.
Add support for Android 4.0.3 and earlier. To do this, specify the parent of the Activity you're starting by adding a 
<meta-data> element as the child of the <activity>.
For this element, set android:name="android.support.PARENT_ACTIVITY". Set android:value="<parent_activity_name>" where <parent_activity_name> is the value of android:name for the parent <activity> element. See the following XML for an example.
Also add support for Android 4.1 and later. To do this, add the android:parentActivityName attribute to the <activity> element of the Activity you're starting.
The final XML should look like this:

<activity
    android:name=".MainActivity"
    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=".ResultActivity"
    android:parentActivityName=".MainActivity">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainActivity"/>
</activity>

Create a back stack based on the Intent that starts the Activity:
Create the Intent to start the Activity.
Create a stack builder by calling TaskStackBuilder.create().
Add the back stack to the stack builder by calling addParentStack(). For each Activity in the hierarchy you've defined in the manifest, the back stack contains an Intent object that starts the Activity. This method also adds flags that start the stack in a fresh task.
Note: Although the argument to addParentStack() is a reference to the started Activity, the method call doesn't add the Intent that starts the Activity. Instead, that's taken care of in the next step.

Add the Intent that starts the Activity from the notification, by calling addNextIntent(). Pass the Intent you created in the first step as the argument to addNextIntent().
If you need to, add arguments to Intent objects on the stack by calling TaskStackBuilder.editIntentAt(). This is sometimes necessary to ensure that the target Activity displays meaningful data when the user navigates to it using Back.
Get a PendingIntent for this back stack by calling getPendingIntent(). You can then use this PendingIntent as the argument to setContentIntent().
The following code snippet demonstrates the process:

...
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
...
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, builder.build());

Setting up a special activity PendingIntent
The following section describes how to set up a special activity PendingIntent.

A special Activity doesn't need a back stack, so you don't have to define its Activity hierarchy in the manifest, and you don't have to call addParentStack() to build a back stack. Instead, use the manifest to set up the Activity task options, and create the PendingIntent by calling getActivity():

In your manifest, add the following attributes to the <activity> element for the Activity
android:name="activityclass"
The activity's fully-qualified class name.
android:taskAffinity=""
Combined with the FLAG_ACTIVITY_NEW_TASK flag that you set in code, this ensures that this Activity doesn't go into the application's default task. Any existing tasks that have the application's default affinity are not affected.
android:excludeFromRecents="true"
Excludes the new task from Recents, so that the user can't accidentally navigate back to it.
This snippet shows the element:

<activity
    android:name=".ResultActivity"
...
    android:launchMode="singleTask"
    android:taskAffinity=""
    android:excludeFromRecents="true">
</activity>
...
Build and issue the notification:
Create an Intent that starts the Activity.
Set the Activity to start in a new, empty task by calling setFlags() with the flags FLAG_ACTIVITY_NEW_TASK and FLAG_ACTIVITY_CLEAR_TASK.
Set any other options you need for the Intent.
Create a PendingIntent from the Intent by calling getActivity(). You can then use this PendingIntent as the argument to setContentIntent().

The following code snippet demonstrates the process:
// Instantiate a Builder object.
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Creates an Intent for the Activity
Intent notifyIntent =
        new Intent(this, ResultActivity.class);
// Sets the Activity to start in a new, empty task
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Creates the PendingIntent
PendingIntent notifyPendingIntent =
        PendingIntent.getActivity(
        this,
        0,
        notifyIntent,
        PendingIntent.FLAG_UPDATE_CURRENT);

// Puts the PendingIntent into the notification builder
builder.setContentIntent(notifyPendingIntent);
// Notifications are issued by sending them to the
// NotificationManager system service.
NotificationManager mNotificationManager =
    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Builds an anonymous Notification object from the builder, and
// passes it to the NotificationManager
mNotificationManager.notify(id, builder.build());

Displaying Progress in a Notification
Notifications can include an animated progress indicator that shows users the status of an ongoing operation. If you can estimate how long the operation takes and how much of it is complete at any time, use the "determinate" form of the indicator (a progress bar). If you can't estimate the length of the operation, use the "indeterminate" form of the indicator (an activity indicator).

Progress indicators are displayed with the platform's implementation of the ProgressBar class.

To use a progress indicator on platforms starting with Android 4.0, call setProgress(). For previous versions, you must create your own custom notification layout that includes a ProgressBar view.

The following sections describe how to display progress in a notification using setProgress().

Displaying a fixed-duration progress indicator
To display a determinate progress bar, add the bar to your notification by calling 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(0, 0, false). For example:

...
mNotifyManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Download")
    .setContentText("Download in progress")
    .setSmallIcon(R.drawable.ic_notification);
// Start a lengthy operation in a background thread
new Thread(
    new Runnable() {
        @Override
        public void run() {
            int incr;
            // Do the "lengthy" operation 20 times
            for (incr = 0; incr <= 100; incr+=5) {
                    // Sets the progress indicator to a max value, the
                    // current completion percentage, and "determinate"
                    // state
                    mBuilder.setProgress(100, incr, false);
                    // Displays the progress bar for the first time.
                    mNotifyManager.notify(0, mBuilder.build());
                        // Sleeps the thread, simulating an operation
                        // that takes time
                        try {
                            // Sleep for 5 seconds
                            Thread.sleep(5*1000);
                        } catch (InterruptedException e) {
                            Log.d(TAG, "sleep failure");
                        }
            }
            // When the loop is finished, updates the notification
            mBuilder.setContentText("Download complete")
            // Removes the progress bar
                    .setProgress(0,0,false);
            mNotifyManager.notify(ID, mBuilder.build());
        }
    }
// Starts the thread by calling the run() method in its Runnable
).start();

Displaying a continuing activity indicator
To display an indeterminate activity indicator, add it to your notification with setProgress(0, 0, true) (the first two arguments are ignored), and issue the notification. The result is an indicator that has the same style as a progress bar, except that its animation is ongoing.

Issue the notification at the beginning of the operation. The animation will run until you modify your notification. When the operation is done, call setProgress(0, 0, false) and then update the notification to remove the activity indicator. Always do this; otherwise, the animation will run even when the operation is complete. Also remember to change the notification text to indicate that the operation is complete.

To see how activity indicators work, refer to the preceding snippet. Locate the following lines:

// Sets the progress indicator to a max value, the current completion
// percentage, and "determinate" state
mBuilder.setProgress(100, incr, false);
// Issues the notification
mNotifyManager.notify(0, mBuilder.build());
Replace the lines you've found with the following lines:

 // Sets an activity indicator for an operation of indeterminate length
mBuilder.setProgress(0, 0, true);
// Issues the notification
mNotifyManager.notify(0, mBuilder.build());
Notification Metadata
Notifications may be sorted according to metadata that you assign with the following NotificationCompat.Builder methods:

setCategory() tells the system how to handle your app notifications when the device is in Priority mode (for example, if your notification represents an incoming call, instant message, or alarm).
setPriority() causes notifications with the priority field set to PRIORITY_MAX or PRIORITY_HIGH to appear in a small floating window if the notification also has sound or vibration.
addPerson() allows you to add a list of people to a notification. Your app can use this to signal to the system that it should group together notifications from the specified people, or rank notifications from these people as being more important.


Heads-up Notifications
With Android 5.0 (API level 21), notifications can appear in a small floating window (also called a heads-up notification) when the device is active (that is, the device is unlocked and its screen is on). These notifications appear similar to the compact form of your notification, except that the heads-up notification also shows action buttons. Users can act on, or dismiss, a heads-up notification without leaving the current app.


Examples of conditions that may trigger heads-up notifications include:

The user's activity is in fullscreen mode (the app uses fullScreenIntent), or
The notification has high priority and uses ringtones or vibrations

Lock Screen Notifications
With the release of Android 5.0 (API level 21), notifications may now appear on the lock screen. Your app can use this functionality to provide media playback controls and other common actions. Users can choose via Settings whether to display notifications on the lock screen, and you can designate whether a notification from your app is visible on the lock screen.



Setting Visibility
Your app can control the level of detail visible in notifications displayed on a secure lock screen. You call setVisibility() and specify one of the following values:

VISIBILITY_PUBLIC shows the notification's full content.
VISIBILITY_SECRET doesn't show any part of this notification on the lock screen.
VISIBILITY_PRIVATE shows basic information, such as the notification's icon and the content title, but hides the notification's full content.

When VISIBILITY_PRIVATE is set, you can also provide an alternate version of the notification content which hides certain details. For example, an SMS app might display a notification that shows You have 3 new text messages, but hides the message contents and senders. To provide this alternative notification, first create the replacement notification using NotificationCompat.Builder. When you create the private notification object, attach the replacement notification to it through the setPublicVersion() method.

Controlling Media Playback on the Lock Screen
In Android 5.0 (API level 21) the lock screen no longer displays media controls based on the RemoteControlClient, which is now deprecated. Instead, use the Notification.MediaStyle template with the addAction() method, which converts actions into clickable icons.

Note: The template and the addAction() method are not included in the support library, so these features run in Android 5.0 and higher only.

To display media playback controls on the lock screen in Android 5.0, set the visibility to VISIBILITY_PUBLIC, as described above. Then add the actions and set the Notification.MediaStyle template, as described in the following sample code:

Notification notification = new Notification.Builder(context)
    // Show controls on lock screen even when user hides sensitive content.
    .setVisibility(Notification.VISIBILITY_PUBLIC)
    .setSmallIcon(R.drawable.ic_stat_player)
    // Add media control buttons that invoke intents in your media service
    .addAction(R.drawable.ic_prev, "Previous", prevPendingIntent) // #0
    .addAction(R.drawable.ic_pause, "Pause", pausePendingIntent)  // #1
    .addAction(R.drawable.ic_next, "Next", nextPendingIntent)     // #2
    // Apply the media style template
    .setStyle(new Notification.MediaStyle()
    .setShowActionsInCompactView(1 /* #1: pause button */)
    .setMediaSession(mMediaSession.getSessionToken())
    .setContentTitle("Wonderful music")
    .setContentText("My Awesome Band")
    .setLargeIcon(albumArtBitmap)
    .build();

Note: The deprecation of RemoteControlClient has further implications for controlling media. See Media Playback Control for more information about the new APIs for managing the media session and controlling playback.

Custom Notification Layouts
The notifications framework allows you to define a custom notification layout, which defines the notification's appearance in a RemoteViews object. Custom layout notifications are similar to normal notifications, but they're based on a RemoteViews defined in a XML layout file.

The height available for a custom notification layout depends on the notification view. Normal view layouts are limited to 64 dp, and expanded view layouts are limited to 256 dp.

To define a custom notification layout, start by instantiating a RemoteViews object that inflates an XML layout file. Then, instead of calling methods such as setContentTitle(), call setContent(). To set content details in the custom notification, use the methods in RemoteViews to set the values of the view's children:

Create an XML layout for the notification in a separate file. You can use any file name you wish, but you must use the extension .xml
In your app, use RemoteViews methods to define your notification's icons and text. Put this RemoteViews object into your NotificationCompat.Builder by calling setContent(). Avoid setting a background Drawable on your RemoteViews object, because your text color may become unreadable.
The RemoteViews class also includes methods that you can use to easily add a Chronometer or ProgressBar to your notification's layout. For more information about creating custom layouts for your notification, refer to the RemoteViews reference documentation.

Caution: When you use a custom notification layout, take special care to ensure that your custom layout works with different device orientations and resolutions. While this advice applies to all View layouts, it's especially important for notifications because the space in the notification drawer is very restricted. Don't make your custom layout too complex, and be sure to test it in various configurations.

Using style resources for custom notification text
Always use style resources for the text of a custom notification. The background color of the notification can vary across different devices and versions, and using style resources helps you account for this. Starting in Android 2.3, the system defined a style for the standard notification layout text. If you use the same style in applications that target Android 2.3 or higher, you'll ensure that your text is visible against the display background.

To get Full Code Click Here

Different format of  Notification:

                                                       1)Big Text Notification


2)Normal Notification


3)Big Picture Notification




4)Inbox Style Notification