Sunday, 27 January 2013

StatusBar Notification in Android

activity_main.xml:

<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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="96dp"
        android:text="Send Notification" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="81dp"
        android:text="Stop Notification" />

</RelativeLayout>

MainActivity.java:
package com.statusbarnotification.ram;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
NotificationManager notificationManager;
Notification notification;
int NOTIFICATION_ID = 1;

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

Button sendNotification = (Button) findViewById(R.id.button1);
Button stopNotification = (Button) findViewById(R.id.button2);

notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

int icon = R.drawable.player;

String tickerText = "hi you have notification";

long when = System.currentTimeMillis();

notification = new Notification(icon, tickerText, when);

Intent in = new Intent(getApplicationContext(), MainActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, in, 0);

String contentTitle = "Notification title";

String contentText = "Notification description";

notification.setLatestEventInfo(getApplicationContext(), contentTitle,
contentText, pendingIntent);

sendNotification.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notificationManager.notify(NOTIFICATION_ID, notification);
}
});
stopNotification.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notificationManager.cancel(NOTIFICATION_ID);
}
});
}

}