Status Bar Notification

Status Bar Notification

A simple example to implement a Status Bar Notification

main.xml
<?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="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/fire"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- Fire Notification -"
/>
</LinearLayout>


AndroidStatusBarNotifications.java
package com.AndroidStatusBarNotifications;

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.widget.Button;

public class AndroidStatusBarNotifications extends Activity {

private static final int ID_My_Notification = 1;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonFire = (Button)findViewById(R.id.fire);
buttonFire.setOnClickListener(buttonFireOnClickListener);
}

private Button.OnClickListener buttonFireOnClickListener
= new Button.OnClickListener(){

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

//Get a reference to the NotificationManager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

//Instantiate the Notification
int icon = android.R.drawable.ic_dialog_alert;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();

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

//Define the Notification's expanded message and Intent
Context context = getApplicationContext();
CharSequence contentTitle = "My Notification";
CharSequence contentText = "Hello My Notification!";
//Intent notificationIntent = new Intent(AndroidStatusBarNotifications.this, AndroidStatusBarNotifications.class);
Intent notificationIntent = new Intent(getBaseContext(), AndroidStatusBarNotifications.class);
PendingIntent contentIntent = PendingIntent.getActivity(AndroidStatusBarNotifications.this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

//Pass the Notification to the NotificationManager
mNotificationManager.notify(ID_My_Notification, notification);

}};
}




0 Response to "Status Bar Notification"

Posting Komentar