android - Notifications

来源:互联网 发布:wow数据库黑翼之巢 编辑:程序博客网 时间:2024/05/20 17:59

A notification is a message you can display to the user outside of your application's normal UI.

You specify the UI information and actions for a notification in a NotificationCompat.Builder object. To create the notification itself, you call NotificationCompat.Builder.build(), which returns a Notificationobject containing your specifications. To issue the notification, you pass the Notification object to the system by calling NotificationManager.notify().

Notification object must contain the following:

  • A small icon, set by setSmallIcon()
  • A title, set by setContentTitle()
  • Detail text, set by setContentText()

>A notification can provide multiple actions. You should always define the action that's triggered when the user clicks the notification; usually this action opens an Activity in your application. You can also add buttons to the notification that perform additional actions such as snoozing an alarm or responding immediately to a text message; this feature is available as of Android 4.1. 

Inside a Notification, the action itself is defined by a PendingIntent containing an Intent that starts anActivity in your application. To associate the PendingIntent with a gesture, call the appropriate method ofNotificationCompat.Builder.

If you wish, you can set the priority of a notification. The priority acts as a hint to the device UI about how the notification should be displayed. To set a notification's priority, callNotificationCompat.Builder.setPriority() and pass in one of the NotificationCompat priority constants. There are five priority levels, ranging from PRIORITY_MIN (-2) to PRIORITY_MAX (2); if not set, the priority defaults to PRIORITY_DEFAULT (0).

NotificationCompat.Builder mBuilder =        new NotificationCompat.Builder(this)        .setSmallIcon(R.drawable.notification_icon)        .setContentTitle("My notification")        .setContentText("Hello World!");// Creates an explicit intent for an Activity in your appIntent resultIntent = new Intent(this, ResultActivity.class);// The stack builder object will contain an artificial back stack for the// started Activity.// This ensures that navigating backward from the Activity leads out of// your application to the Home screen.TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);// Adds the back stack for the Intent (but not the Intent itself)stackBuilder.addParentStack(ResultActivity.class);// Adds the Intent that starts the Activity to the top of the stackstackBuilder.addNextIntent(resultIntent);PendingIntent resultPendingIntent =        stackBuilder.getPendingIntent(            0,            PendingIntent.FLAG_UPDATE_CURRENT        );mBuilder.setContentIntent(resultPendingIntent);NotificationManager mNotificationManager =    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);// mId allows you to update the notification later on.mNotificationManager.notify(mId, mBuilder.build());
>a notification that is updated to reflect the number of events 

mNotificationManager =        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);// Sets an ID for the notification, so it can be updatedint notifyID = 1;mNotifyBuilder = new NotificationCompat.Builder(this)    .setContentTitle("New Message")    .setContentText("You've received new messages.")    .setSmallIcon(R.drawable.ic_notify_status)numMessages = 0;// Start of a loop that processes data and then notifies the user...    mNotifyBuilder.setContentText(currentText)        .setNumber(++numMessages);    // Because the ID remains unchanged, the existing notification is    // updated.    mNotificationManager.notify(            notifyID,            mNotifyBuilder.build());...
<activity    android:name=".MainActivity"    android:label="@string/app_name" >    <intent-filter>        <action android:name="android.intent.action.MAIN" />        <category android:name="android.intent.category.LAUNCHER" />    </intent-filter></activity><activity    android:name=".ResultActivity"    android:parentActivityName=".MainActivity">    <meta-data        android:name="android.support.PARENT_ACTIVITY"        android:value=".MainActivity"/></activity>
Create a back stack based on the Intent that starts the Activity:
  1. Create the Intent to start the Activity.
  2. Create a stack builder by calling TaskStackBuilder.create().
  3. Add the back stack to the stack builder by calling addParentStack(). For each Activity in the hierarchy you've defined in the manifest, the back stack contains an Intent object that starts theActivity. This method also adds flags that start the stack in a fresh task.

    Note: Although the argument to addParentStack() is a reference to the started Activity, the method call doesn't add the Intent that starts the Activity. Instead, that's taken care of in the next step.

  4. Add the Intent that starts the Activity from the notification, by calling addNextIntent(). Pass theIntent you created in the first step as the argument to addNextIntent().
  5. If you need to, add arguments to Intent objects on the stack by callingTaskStackBuilder.editIntentAt(). This is sometimes necessary to ensure that the target Activitydisplays meaningful data when the user navigates to it using Back.
  6. Get a PendingIntent for this back stack by calling getPendingIntent(). You can then use thisPendingIntent as the argument to setContentIntent().
Intent resultIntent = new Intent(this, ResultActivity.class);TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);// Adds the back stackstackBuilder.addParentStack(ResultActivity.class);// Adds the Intent to the top of the stackstackBuilder.addNextIntent(resultIntent);// Gets a PendingIntent containing the entire back stackPendingIntent resultPendingIntent =        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);...NotificationCompat.Builder builder = new NotificationCompat.Builder(this);builder.setContentIntent(resultPendingIntent);NotificationManager mNotificationManager =    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mNotificationManager.notify(id, builder.build());
// Instantiate a Builder object.NotificationCompat.Builder builder = new NotificationCompat.Builder(this);// Creates an Intent for the ActivityIntent notifyIntent =        new Intent(this, ResultActivity.class);// Sets the Activity to start in a new, empty tasknotifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK                        | Intent.FLAG_ACTIVITY_CLEAR_TASK);// Creates the PendingIntentPendingIntent notifyPendingIntent =        PendingIntent.getActivity(        this,        0,        notifyIntent,        PendingIntent.FLAG_UPDATE_CURRENT);// Puts the PendingIntent into the notification builderbuilder.setContentIntent(notifyPendingIntent);// Notifications are issued by sending them to the// NotificationManager system service.NotificationManager mNotificationManager =    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);// Builds an anonymous Notification object from the builder, and// passes it to the NotificationManagermNotificationManager.notify(id, builder.build());
 Then add the actions and set the Notification.MediaStyle template:
Notification notification = new Notification.Builder(context)    // Show controls on lock screen even when user hides sensitive content.    .setVisibility(Notification.VISIBILITY_PUBLIC)    .setSmallIcon(R.drawable.ic_stat_player)    // Add media control buttons that invoke intents in your media service    .addAction(R.drawable.ic_prev, "Previous", prevPendingIntent) // #0    .addAction(R.drawable.ic_pause, "Pause", pausePendingIntent)  // #1    .addAction(R.drawable.ic_next, "Next", nextPendingIntent)     // #2    // Apply the media style template    .setStyle(new Notification.MediaStyle()    .setShowActionsInCompactView(1 /* #1: pause button */)    .setMediaSession(mMediaSession.getSessionToken())    .setContentTitle("Wonderful music")    .setContentText("My Awesome Band")    .setLargeIcon(albumArtBitmap)    .build();

0 0
原创粉丝点击