Android Notifications

Android Notifications

Android notifications is a note you can screen to an individual beyond your application’s normal User Interface. Whenever you notify the functional system to concern a notification, it seems as an icon in the notification area first. To start to see the information on the notification, the notification is exposed by an individual drawer. Notification area and the notification drawer both are the system-controlled areas that an individual can view anytime.

android notifications

Android OS Toast class offers a useful way showing users notifications but problem is these alerts aren’t persistent this means alert flashes on the display for a couple of seconds and then invisible.

android notifications

To start to see the information on the notification, you will need to choose the icon that may screen notification drawer having details about the notification. While dealing with emulator with exclusive device, you will need to click and move down the position bar to increase it that will give you depth as follows. This can be just 64 dp extra tall and called it is normal view

android notifications

Broadened form (given above) can have a Big View that may have additional fine detail about the android notifications. You can include up-to six additional lines in the notification. The next display shot shows such notification or alerts.

How To Create Android Notifications and Send Notifications

You could have simple way to make a notification. Follow the next steps in the application to make a notification

Step 1 – Create Android Notifications Builder

As an initial step is to make a notification contractor using NotificationCompat.Constructor.build(). You use Notification Contractor to create various Notification properties like its small and large symbols, title, concern etc.

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)

 

Step 2 – Setting Android Notifications Properties

When you’ve Builder object, you can placed its Notification properties by using Builder object according to your need. But this is necessary to create at least following

  • A small icon, set bysetSmallIcon()
  • A title, set bysetContentTitle()
  • Detail text, set bysetContentText()
mBuilder.setSmallIcon(R.drawable.notification_icon);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");

 

You have lots of optional properties which you can establish for your notification. To find out more on them, start to see the reference documents for NotificationCompat.Builder

Step 3 – Attach Actions

This step is an optional part and required if you wish to add an action with the notification. An action allows users to look from the notification to an Activity in the application immediately, where they can look at a number of events or do further work.

The action is described with a PendingIntent comprising an Intent that starts a task/Activity in the application. To relate the PendingIntent with a gesture, call the correct approach to NotificationCompat.Builder. For instance, if you need to start out Activity when an individual clicks the notification wording in the notification drawer, you add the PendingIntent by getting in touch with setContentIntent().

A PendingIntent object allows you to perform an action on your applications behalf, at another time often, without caring of if the application is running.

We take help of stack constructor object that may contain an unnatural backside stack for the began Activity. This means that navigating backward from the experience leads out of the application to the home display screen.

Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
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);

Step 4 – Issue the android notifications

At last, you cross the Notification object to the machine by contacting NotificationManager.notify() to send your notification. Be sure you NotificationCompat call.Builder.build() method on constructor subject before notifying it. This technique combines all the options which may have been arranged and return a fresh Notification object.

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
// notificationID allows you to update the notification later on.
mNotificationManager.notify(notificationID, mBuilder.build());

 

Android Notifications Example

Pursuing android notifications example shows the operation of a Android os notification by using a NotificationCompat.Builder School which includes been launched in Android os 4.1.

Steps       Description

1- You use Android studio IDE to generate an Android software and name it as androdevelopment under a deal com.example.notificationdemo. While creating this task, ensure you Focus on SDK and Compile With at the latest version of Google android SDK to utilize higher levels/degrees of APIs.

2- Modify src/MainActivity.java &  add the code to notify(“”), if customer go through the button,it’ll call android notification service.

3- Create a fresh Java data file src/NotificationView.java, which is used to show new layout as part of new activity which is started when end user will click the notifications

4- Modify design XML data file res/structure/activity_main.xml to include Notification button in comparative layout.

5- Create a fresh layout XML res/design/notification.xml. This may be utilized as layout apply for new activity that may start when consumer will click the notifications.

6- No need to improve default string constants. Android os studio manages default string constants

7- Run the application form to launch Google android emulator and check the consequence of the changes done in the application form.

Following is the content of the modified main activity file src/com.example.notificationdemo/MainActivity.java. This file can include each of the fundamental android life-cycle methods.

package com.example.notificationdemo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {
   Button b1;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      b1=(Button)findViewById(R.id.button);
      b1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Notify("You have received new message");
         }
      });
   }
   private void Notify(String notificationTitle, String notificationMessage){
      NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      @SuppressWarnings("deprecation")
      
      Notification notification = new Notification(R.drawable.abc,"New Message", System.currentTimeMillis());
      Intent notificationIntent = new Intent(this,NotificationView.class);
      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,notificationIntent, 0);
      
      notification.setLatestEventInfo(MainActivity.this, notificationTitle,notificationMessage, pendingIntent);
      notificationManager.notify(9999, notification);
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

 

Following will be the content of res/layout/notification.xml file:


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent" >
   
   <TextView
      android:layout_width="fill_parent"
      android:layout_height="400dp"
      android:text="Hi, Your Detailed notification view goes here...." />
</LinearLayout>

 

Following is the content of the modified main activity file src/com.example.notificationdemo/NotificationView.java.

package com.example.notificationdemo;

import android.os.Bundle;
import android.app.Activity;

public class NotificationView extends Activity{
   @Override
   public void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.notification);
   }
}

 

Following will be the content of res/layout/activity_main.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context="MainActivity">
   
   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Notification Example"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true"
      android:textSize="30dp" />
      
   <TextView
      android:id="@+id/textView2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Andro Development "
      android:textColor="#ff87ff09"
      android:textSize="30dp"
      android:layout_below="@+id/textView1"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="48dp" />
      
   <ImageButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageButton"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="42dp" />
      
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Notification"
      android:id="@+id/button"
      android:layout_marginTop="62dp"
      android:layout_below="@+id/imageButton"
      android:layout_centerHorizontal="true" />
      
</RelativeLayout>

 

Following will be the content of res/values/strings.xml to define two new constants −

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <string name="action_settings">Settings</string>
   <string name="app_name">androdevelopment </string>  
</resources>

 

Following is the default content of AndroidManifest.xml −

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.notificationdemo"
   android:versionCode="1"
   android:versionName="1.0" >
   
   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.notificationdemo.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=".NotificationView"
         android:label="Details of notification"
         android:parentActivityName=".MainActivity">
         <meta-data
         android:name="android.support.PARENT_ACTIVITY"
         android:value=".MainActivity"/>
      </activity>
      
   </application>
</manifest>

 

How about we attempt to run our androdevelopment application we simply created. I accept you had made your AVD while doing android environment setup. To run the application from Android studio, open one of your project activity file and snap  Android Studio Run Icon    from the tool bar. Android Studio installs the application on your AVD and begins it and if all is well with your set-up and application, it will show taking after Emulator window

android notifications

Click button now, you will notice at the very top a note “New Subject matter Alert!” will screen momentarily and you then will have pursuing screen having a tiny icon at the very top left corner.

Now enables grow the view, long go through the small icon, after another it will screen date information which is enough time when you should pull status club down without liberating mouse. You shall see position pub will expand and you’ll get pursuing display

android notifications

Big View Android Notifications

The next code snippet shows how to improve the notification created in the last snippet to work with the Inbox big view style. I’ll update displayNotification() adjustment solution to show this efficiency

protected void displayNotification() {
   Log.i("Start", "notification");

   /* Invoking the default notification service */
   NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(this);
   
   mBuilder.setContentTitle("New Message");
   mBuilder.setContentText("You've received new message.");
   mBuilder.setTicker("New Message Alert!");
   mBuilder.setSmallIcon(R.drawable.woman);
   
   /* Increase notification number every time a new notification arrives */
   mBuilder.setNumber(++numMessages);
   
   /* Add Big View Specific Configuration */
   NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
   
   String[] events = new String[6];
   events[0] = new String("This is first line....");
   events[1] = new String("This is second line...");
   events[2] = new String("This is third line...");
   events[3] = new String("This is 4th line...");
   events[4] = new String("This is 5th line...");
   events[5] = new String("This is 6th line...");
   
   // Sets a title for the Inbox style big view
   inboxStyle.setBigContentTitle("Large Title Details:");
   
   // Moves events into the big view
   for (int i=0; i < events.length; i++) {
      inboxStyle.addLine(events[i]);
   }
   
   mBuilder.setStyle(inboxStyle);
   
   /* Creates an explicit intent for an Activity in your app */
   Intent resultIntent = new Intent(this, NotificationView.class);
   
   TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
   stackBuilder.addParentStack(NotificationView.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);
   mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
   
   /* notificationID allows you to update the notification later on. */
   mNotificationManager.notify(notificationID, mBuilder.build());
}

 

Now if you will attempt to run the application then you will see following bring about broadened form of the view

android-notifications


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed