How to implement local Notification in Android.

Create New Project

1. First create a new project in Android Studio (File => New Project)

activity_main.xml

									   
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:fitsSystemWindows="true"
    tools:context="com.example.samsung.notify.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Notification"
        android:id="@+id/button"
        android:textSize="25dp"
        android:onClick="notify"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="199dp" />
</RelativeLayout>

MainActivity.java

									   
package com.example.samsung.notify;

import android.app.Notification;
import android.app.NotificationManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    int count = 0;

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

    public void notify(View view) {
        count++;
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notify = new Notification.Builder(MainActivity.this)
                .setContentTitle("New MSG")
                .setContentText("You got new message")
                .setSmallIcon(R.drawable.msg).build();

        manager.notify(count, notify);
    }
}

Output :

Tags

  • Android

  • Android Studio

  • Android development

  • Java