Monday, June 25, 2018

Android Local Status Bar Notification – Example


A Notification is a message which is displayed in the Notification drawer and Notification Ticker is shown in the Status bar. In this tutorial we are going to see how to send Notifications from your Android Application and open the Notification in a new Activity.

Creating Project

Make sure you have properly Setup the Android SDK, AVD for Testing the Application. Its better to have a physical device for testing. Create a New project in Eclipse IDE with the package as com.abhinand.localnotification Create the Main Activity as MainActivity and the main Layout as activity_main.




Creating Layout

The main layout activity_main has a Button to send notification.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Android Notification"
        android:textSize="30sp" />

    <Button
        android:id="@+id/SendNotificationBTN"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Send Notification" />

</LinearLayout>
We need to create a new layout for the Result Activity which is opened when the notification is clicked.

result.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView android:id="@+id/ResultTV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:text="Android Notificaton" />
</LinearLayout>

Creating Activity

The notification is sent when the button is clicked. It is initialised by the function startNotification() . We use NotificationCompat builder to create the notification. setContentTitle() is used to set the title message. setContentText() is used to set the notification message. setTicker() is is used to set the Alert message. setSmallIcon() is used to set a icon image for our Notification. Result.java is the result class which is Initialised, and it opens when the notification is clicked. build() is used to display the notification.

MainActivity.java

package com.abhinand.localnotification;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatDelegate;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button SendnotificationBTN;
    NotificationCompat.Builder notification;
    PendingIntent pIntent;
    NotificationManager manager;
    Intent resultIntent;
    TaskStackBuilder stackBuilder;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

        SendnotificationBTN = (Button)findViewById(R.id.SendNotificationBTN);
        SendnotificationBTN.setOnClickListener(new View.OnClickListener() {

            @Override            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                startNotification();

            }

            protected void startNotification() {
                // TODO Auto-generated method stub
                //Creating Notification Builder
                notification = new NotificationCompat.Builder(MainActivity.this,"AndroidHelperChannel1");
                //Title for Notification
                notification.setContentTitle("Android Helper Updates");
                //Message in the Notification
                notification.setContentText("New Post on Android Local Notification.");
                //Alert shown when Notification is received
                notification.setTicker("New Message Alert!");
                //Icon to be set on Notification
                notification.setSmallIcon(R.drawable.ic_mail);
                //Creating new Stack Builder
                stackBuilder = TaskStackBuilder.create(MainActivity.this);
                stackBuilder.addParentStack(Result.class);
                //Intent which is opened when notification is clicked
                resultIntent = new Intent(MainActivity.this, Result.class);
                stackBuilder.addNextIntent(resultIntent);
                pIntent =  stackBuilder
                .getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
                notification.setContentIntent(pIntent);
                manager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                manager.notify(0, notification.build());

            }
        });


    }
}
And our next Activity is Result which is given by Result.java. Add the following to Manifest to define Result Activity.

 Result.java

package com.abhinand.localnotification;

import android.app.NotificationManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Result extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);

        NotificationManager notificationManager = 
       (NotificationManager) getApplicationContext()
       .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(0);
    }
}

Creating Manifest

We do not need any special permissions for our project. Add the meta to the Manifest.
  <meta-data
  android:name="android.support.PARENT_ACTIVITY"
  android:value=".MainActivity"/>

 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.abhinand.localnotification">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Result"></activity>
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity"/>
    </application>

</manifest>