Monday, 20 August 2012

Notification - Android

Here I am presenting simple example of notification in android. In android notification is shown in status bar at the top of screen. For this purpose we don't need to set any permission. Here is code for notification in android,

Notify.java

package com.android;


import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Notify extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button notificationButton = (Button)findViewById(R.id.notificationButton);
        notificationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        notification("Title","Message");
                    }
                },0);
            }
        });
    }

    // Notification Function
    private void notification(String notificationTitle, String notificationMessage) {
        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new Notification(R.drawable.icon, "A New Message!", System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, Notify.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(Notify.this, notificationTitle, notificationMessage, pendingIntent);
        notificationManager.notify(10001, notification);
    }
}

and here is main.xml file,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
   
     <TextView android:text="Notification Example"
     android:id="@+id/TextView01"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"/>
   
     <Button
     android:id="@+id/notificationButton"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="Notify"/>
</LinearLayout>

That's all you have to for notification.

No comments:

Post a Comment