Android Tutorial - Core Class : Notification

 Notification event

package com.commonsware.android.notify;

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;
import java.util.Timer;
import java.util.TimerTask;

public class NotifyDemo extends Activity {
  private static final int NOTIFY_ME_ID=1337;
  private Timer timer=new Timer();
  private int count=0;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    Button btn=(Button)findViewById(R.id.notify);
    
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        TimerTask task=new TimerTask() {
          public void run() {
            notifyMe();
          }
        };
    
        timer.schedule(task, 5000);
      }
    });
    
    btn=(Button)findViewById(R.id.cancel);
    
    btn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        NotificationManager mgr=
          (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
          
        mgr.cancel(NOTIFY_ME_ID);
      }
    });
  }
  
  private void notifyMe() {
    final NotificationManager mgr=
      (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    Notification note=new Notification(R.drawable.red_ball,
                                        "Status message!",
                                        System.currentTimeMillis());
    PendingIntent i=PendingIntent.getActivity(this, 0,
                            new Intent(this, NotifyMessage.class),
                                              0);
    
    note.setLatestEventInfo(this, "Notification Title",
                            "This is the notification message", i);
    note.number=++count;
    
    mgr.notify(NOTIFY_ME_ID, note);
  }
}


package com.commonsware.android.notify;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class NotifyMessage extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    TextView txt=new TextView(this);
    
    txt.setText("This is the message!");
    setContentView(txt);
  }
}



//res\layout\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"
    >
  <Button android:id="@+id/notify"
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:layout_weight="1"
      android:text="Click to raise a notification in 5 seconds"
      />
  <Button android:id="@+id/cancel"
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:layout_weight="1"
      android:text="Click to clear the notification"
      />
</LinearLayout>

Look up the notification manager service

  
package app.test;

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;

import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;

 class NotificationView extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.row);
            
        NotificationManager nm = (NotificationManager) 
            getSystemService(NOTIFICATION_SERVICE);
        nm.cancel(getIntent().getExtras().getInt("notificationID"));
    }
}
public class Test extends Activity {
  int notificationID = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button button = (Button) findViewById(R.id.btn_displaynotif);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                displayNotification();     
            }
        });    
    }
    
    protected void displayNotification()
    {
      Intent i = new Intent(this, NotificationView.class);
      i.putExtra("notificationID", notificationID);    
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);        
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 
        Notification notif = new Notification(
            R.drawable.icon, 
            "Reminder: Meeting starts in 5 minutes",
            System.currentTimeMillis());

        CharSequence from = "System Alarm";
        CharSequence message = "Meeting with customer at 3pm...";
        
        notif.setLatestEventInfo(this, from, message, pendingIntent);

        notif.vibrate = new long[] { 100, 250, 100, 500};
        nm.notify(notificationID, notif);        
    }
}

//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" >
<Button 
    android:id="@+id/btn_displaynotif"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Display Notification" />
</LinearLayout>
//row.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="Here are the details for the notification..." />
</LinearLayout>

Cancel the notification that we started

  
package app.test;

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;

import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;

 class NotificationView extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.row);
            
        NotificationManager nm = (NotificationManager) 
            getSystemService(NOTIFICATION_SERVICE);
        nm.cancel(getIntent().getExtras().getInt("notificationID"));
    }
}
public class Test extends Activity {
  int notificationID = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button button = (Button) findViewById(R.id.btn_displaynotif);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                displayNotification();     
            }
        });    
    }
    
    protected void displayNotification()
    {
      Intent i = new Intent(this, NotificationView.class);
      i.putExtra("notificationID", notificationID);    
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i, 0);        
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 
        Notification notif = new Notification(
            R.drawable.icon, 
            "Reminder: Meeting starts in 5 minutes",
            System.currentTimeMillis());

        CharSequence from = "System Alarm";
        CharSequence message = "Meeting with customer at 3pm...";
        
        notif.setLatestEventInfo(this, from, message, pendingIntent);

        notif.vibrate = new long[] { 100, 250, 100, 500};
        nm.notify(notificationID, notif);        
    }
}

//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" >
<Button 
    android:id="@+id/btn_displaynotif"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Display Notification" />
</LinearLayout>
//row.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="Here are the details for the notification..." />
</LinearLayout>

Using NotificationManager

  


package app.test;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

class TestService extends Service {

  private static final String TAG = "TestService";
  private NotificationManager _nm;

  @Override
  public IBinder onBind(Intent i) {
    Log.e(TAG, "TestService.onBind");
    return null;
  }

  public class LocalBinder extends Binder {
    TestService getService() {
      return TestService.this;
    }
  }

  @Override
  public boolean onUnbind(Intent i) {
    Log.e(TAG, "TestService.onUnbind");
    return false;
  }

  @Override
  public void onRebind(Intent i) {
    Log.e(TAG, "TestService.onRebind");
  }

  @Override
  public void onCreate() {
    Log.e(TAG, "TestService.onCreate");
    _nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();
  }

  @Override
  public void onStart(Intent intent, int startId) {
    Log.e(TAG, "TestService.onStart");
  }

  @Override
  public void onDestroy() {
    _nm.cancel(0);
    Log.e(TAG, "TestService.onDestroy");
  }

  private void showNotification() {
    Notification notification = new Notification(R.drawable.icon,
        "Service started", System.currentTimeMillis());

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
        new Intent(this, Test.class), 0);
    notification.setLatestEventInfo(this, "Test Service",
        "Service started", contentIntent);
    _nm.notify(0, notification);
  }
}

public class Test extends Activity {
  private boolean _isBound;
  private TestService _boundService;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    setTitle("Service Test");

    initButtons();

  }
  
    private ServiceConnection _connection = new ServiceConnection() {  
        public void onServiceConnected(ComponentName className, IBinder service) {           
            _boundService = ((TestService.LocalBinder)service).getService();  
              
            Toast.makeText(Test.this, "Service connected",  
                    Toast.LENGTH_SHORT).show();  
        }  
  
        public void onServiceDisconnected(ComponentName className) {  
            _boundService = null;  
            Toast.makeText(Test.this, "Service connected",  
                    Toast.LENGTH_SHORT).show();  
        }  
    };  
    
    private void initButtons() {  
        Button buttonStart = (Button) findViewById(R.id.start_service);  
        buttonStart.setOnClickListener(new OnClickListener() {  
            public void onClick(View arg0) {  
                startService();  
            }  
        });  
  
        Button buttonStop = (Button) findViewById(R.id.stop_service);  
        buttonStop.setOnClickListener(new OnClickListener() {  
            public void onClick(View arg0) {  
                stopService();  
            }  
        });  
  
        Button buttonBind = (Button) findViewById(R.id.bind_service);  
        buttonBind.setOnClickListener(new OnClickListener() {  
            public void onClick(View arg0) {  
                bindService();  
            }  
        });  
  
        Button buttonUnbind = (Button) findViewById(R.id.unbind_service);  
        buttonUnbind.setOnClickListener(new OnClickListener() {  
            public void onClick(View arg0) {  
                unbindService();  
            }  
        });  
    }  
  
    private void startService() {  
        Intent i = new Intent(this, TestService.class);  
        this.startService(i);  
    }  
    
    private void stopService() {  
        Intent i = new Intent(this, TestService.class);  
        this.stopService(i);  
    }  
  
    private void bindService() {  
        Intent i = new Intent(this, TestService.class);  
         bindService(i, _connection, Context.BIND_AUTO_CREATE);  
         _isBound = true;  
    }  
  
    private void unbindService() {  
        if (_isBound) {  
            unbindService(_connection);  
            _isBound = false;  
        }  
    }  
}

//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/start_service" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Start Service" />

  <Button android:id="@+id/stop_service" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Stop Service" />

  <Button android:id="@+id/bind_service" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Bind Service" />

  <Button android:id="@+id/unbind_service" android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:text="Unbind Service" />

</LinearLayout>

Demonstrates adding notifications to the status bar

package com.example.android.apis.app;

import com.example.android.apis.R;

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

/**
 * Demonstrates adding notifications to the status bar
 */
public class StatusBarNotifications extends Activity {

    private NotificationManager mNotificationManager;

    // Use our layout id for a unique identifier
    private static int MOOD_NOTIFICATIONS = R.layout.status_bar_notifications;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.status_bar_notifications);

        Button button;

        // Get the notification manager serivce.
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        button = (Button) findViewById(R.id.happy);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setMood(R.drawable.stat_happy, R.string.status_bar_notifications_happy_message,
                        false);
            }
        });

        button = (Button) findViewById(R.id.neutral);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setMood(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message,
                        false);
            }
        });

        button = (Button) findViewById(R.id.sad);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setMood(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message, false);
            }
        });

        button = (Button) findViewById(R.id.happyMarquee);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setMood(R.drawable.stat_happy, R.string.status_bar_notifications_happy_message,
                        true);
            }
        });

        button = (Button) findViewById(R.id.neutralMarquee);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setMood(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message, true);
            }
        });

        button = (Button) findViewById(R.id.sadMarquee);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setMood(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message, true);
            }
        });

        button = (Button) findViewById(R.id.happyViews);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setMoodView(R.drawable.stat_happy, R.string.status_bar_notifications_happy_message);
            }
        });

        button = (Button) findViewById(R.id.neutralViews);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setMoodView(R.drawable.stat_neutral, R.string.status_bar_notifications_ok_message);
            }
        });

        button = (Button) findViewById(R.id.sadViews);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setMoodView(R.drawable.stat_sad, R.string.status_bar_notifications_sad_message);
            }
        });
        
        button = (Button) findViewById(R.id.defaultSound);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setDefault(Notification.DEFAULT_SOUND);
            }
        });
        
        button = (Button) findViewById(R.id.defaultVibrate);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setDefault(Notification.DEFAULT_VIBRATE);
            }
        });
        
        button = (Button) findViewById(R.id.defaultAll);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                setDefault(Notification.DEFAULT_ALL);
            }
        });
        
        button = (Button) findViewById(R.id.clear);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                mNotificationManager.cancel(R.layout.status_bar_notifications);
            }
        });
    }

    private PendingIntent makeMoodIntent(int moodId) {
        // The PendingIntent to launch our activity if the user selects this
        // notification.  Note the use of FLAG_UPDATE_CURRENT so that if there
        // is already an active matching pending intent, we will update its
        // extras (and other Intents in the array) to be the ones passed in here.
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, NotificationDisplay.class).putExtra("moodimg", moodId),
                PendingIntent.FLAG_UPDATE_CURRENT);
        return contentIntent;
    }
    

    private PendingIntent makeDefaultIntent() {
        // A typical convention for notifications is to launch the user deeply
        // into an application representing the data in the notification; to
        // accomplish this, we can build an array of intents to insert the back
        // stack stack history above the item being displayed.
        Intent[] intents = new Intent[4];

        // First: root activity of ApiDemos.
        // This is a convenient way to make the proper Intent to launch and
        // reset an application's task.
        intents[0] = Intent.makeRestartActivityTask(new ComponentName(this,
                com.example.android.apis.ApiDemos.class));

        // "App"
        intents[1] = new Intent(this, com.example.android.apis.ApiDemos.class);
        intents[1].putExtra("com.example.android.apis.Path", "App");
        // "App/Notification"
        intents[2] = new Intent(this, com.example.android.apis.ApiDemos.class);
        intents[2].putExtra("com.example.android.apis.Path", "App/Notification");

        // Now the activity to display to the user.
        intents[3] = new Intent(this, StatusBarNotifications.class);

        // The PendingIntent to launch our activity if the user selects this
        // notification.  Note the use of FLAG_UPDATE_CURRENT so that if there
        // is already an active matching pending intent, we will update its
        // extras (and other Intents in the array) to be the ones passed in here.
        PendingIntent contentIntent = PendingIntent.getActivities(this, 0,
                intents, PendingIntent.FLAG_UPDATE_CURRENT);
        return contentIntent;
    }


    private void setMood(int moodId, int textId, boolean showTicker) {
        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(textId);

        // choose the ticker text
        String tickerText = showTicker ? getString(textId) : null;

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(moodId, tickerText,
                System.currentTimeMillis());

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, getText(R.string.status_bar_notifications_mood_title),
                       text, makeMoodIntent(moodId));

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNotificationManager.notify(MOOD_NOTIFICATIONS, notification);
    }

    private void setMoodView(int moodId, int textId) {
        // Instead of the normal constructor, we're going to use the one with no args and fill
        // in all of the data ourselves.  The normal one uses the default layout for notifications.
        // You probably want that in most cases, but if you want to do something custom, you
        // can set the contentView field to your own RemoteViews object.
        Notification notif = new Notification();

        // This is who should be launched if the user selects our notification.
        notif.contentIntent = makeMoodIntent(moodId);

        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(textId);
        notif.tickerText = text;

        // the icon for the status bar
        notif.icon = moodId;

        // our custom view
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.status_bar_balloon);
        contentView.setTextViewText(R.id.text, text);
        contentView.setImageViewResource(R.id.icon, moodId);
        notif.contentView = contentView;

        // we use a string id because is a unique number.  we use it later to cancel the
        // notification
        mNotificationManager.notify(MOOD_NOTIFICATIONS, notif);
    }
    
    private void setDefault(int defaults) {
        
        // This method sets the defaults on the notification before posting it.
        
        // This is who should be launched if the user selects our notification.
        PendingIntent contentIntent = makeDefaultIntent();

        // In this sample, we'll use the same text for the ticker and the expanded notification
        CharSequence text = getText(R.string.status_bar_notifications_happy_message);

        final Notification notification = new Notification(
                R.drawable.stat_happy,       // the icon for the status bar
                text,                        // the text to display in the ticker
                System.currentTimeMillis()); // the timestamp for the notification

        notification.setLatestEventInfo(
                this,                        // the context to use
                getText(R.string.status_bar_notifications_mood_title),
                                             // the title for the notification
                text,                        // the details to display in the notification
                contentIntent);              // the contentIntent (see above)

        notification.defaults = defaults;
        
        mNotificationManager.notify(
                MOOD_NOTIFICATIONS, // we use a string id because it is a unique
                                    // number.  we use it later to cancel the notification
                notification);
    }    
}

Send Notification

  

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

 class Helper {
    public static void sendNotification(Context context, int notificationId,
            String title, String content) {
        // Show a notification.
        final NotificationManager nMgr = (NotificationManager) context.getSystemService(
                context.NOTIFICATION_SERVICE);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
        Notification notif = new Notification(R.drawable.icon, title, 
                System.currentTimeMillis());
        notif.setLatestEventInfo(context, title, (content == null) ? "" : content, contentIntent);
        nMgr.notify(notificationId, notif);
    }
}