Android Notification通知详解

Android Notification通知详解

Notification:

(一)、简介:

显示在手机状态栏的通知。Notification所代表的是一种具有全局效果的通知,程序一般通过NotificationManager服务来发送Notification。

Android3.0增加了Notification.Builder类,该类可以轻松地创建Notification对象。

(二)、Notification.Builder类中提供的方法:

builder.setAutoCancel(); 设置点击通知后,状态栏自动删除通知。

builder.setSmallIcon(R.drawable.alert); 设置通知小图标

builder.setLargeIcon(R.drawable.alert2); 设置通知大图标

builder.setContentTitle("标题"); 设置通知标题

builder.setContentText("文本");  设置通知内容

builder.setDefaults(Notification.DEFAULT_SOUND

| Notification.DEFAULT_VIBRATE);  设置通知的音乐、振动、LED等。

builder.setSound();  设置通知的音乐

builder.setTick();  设置通知在状态栏的提示文本

builder.setContentIntent();  设置点击通知后将要启动的程序组件对应的PendingIntent

(三)、发送Notification的步骤:(四部曲)

1、调用getSystemService(NOTIFICATION_SERVICE)方法获取系统的NotificationManager服务,它是一个重要的系统服务。应用程序可以通过NotificationManager 向系统发送全局通知;

2、构造Notification.Builder对象;

3、设置Notification.Builder对象的各种属性;

4、通过NotificationManager 的notify()方法发送Notification。

(四)、示例代码:

核心代码如下:

NotificationManager  manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder = new Notification.Builder(this);
builder.setAutoCancel(true);
builder.setSmallIcon(R.drawable.alert);
builder.setContentTitle("标题");
builder.setContentText("文本");
builder.setDefaults(Notification.DEFAULT_SOUND| Notification.DEFAULT_VIBRATE);
Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 1, intent,PendingIntent.FLAG_ONE_SHOT);
builder.setContentIntent(pIntent);
manager.notify(0, builder.build());

(五)、PendingIntent:

1、PendingIntent字面意义:等待的,悬而未决的Intent;

2、得到一个 PendingIntent 对象,使用方法类的静态方法 getActivity(Context, int, Intent, int);

3、PendingIntent是一种特殊的Intent。主要的区别在于Intent是立刻执行,而 PendingIntent 的执行不是立刻,而是当条件满足后才发送企图,而且PendingIntent 可以取消;

4、PendingIntent执行的操作实质上是参数传进来的Intent的操作,使用 PendingIntent 的目的在于它所包含的Intent的操作的执行是需要满足某些条件的。

5、主要的使用的地方和例子:通知Notificatio的发送,短消息SmsManager的发送和警报器AlarmManager的执行等。

(六)、Intent和PendingIntent的区别:【掌握,以备面试之需】

  1. Intent是立即使用的,而PendingIntent可以等到事件发生后触发,PendingIntent可以cancel;
  2. Intent在程序结束后即终止,而PendingIntent在程序结束后依然有效;
  3. PendingIntent自带Context,而Intent需要在某个Context内运行;
  4. Intent在原task中运行,PendingIntent在新的task中运行。

(七)、PendingIntent的几个常量:(getActivity(Context, int,
Intent, int)方法中的第四个参数)

  1. FLAG_ONE_SHOT  : 这个PendingIntent只能使用一次。
  2. FLAG_NO_CREATE : 如果被描述的PendingIntent不存在,那么简单地返回null,而不是创建它。
  3. FLAG_CANCEL_CURRENT  :  如果被描述的PendingIntent已经存在,在即将生成一个新的PendingIntent前,当前的一个要被取消。
  4. FLAG_UPDATE_CURRENT  :如果被描述的PendingIntent已经存在,那么继续保持它,但它其中的数据会因为新Intent而更新。

设置notification的点击跳转:

NotificationCompat.Builder builder = new NotificationCompat.Builder(

MainActivity.this);

builder.setContentText("344444444444");

builder.setContentTitle("33333333333");

builder.setSmallIcon(R.drawable.ic_launcher);

Intent intent = new Intent(MainActivity.this,

ScondActivity.class);

PendingIntent intent2 = PendingIntent.getActivity(

MainActivity.this, 1, intent,

PendingIntent.FLAG_CANCEL_CURRENT);

builder.setContentIntent(intent2);

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(1, builder.build());

 /**
     * 在状态栏显示通知
     */
    private void showNotification(){
        // 创建一个NotificationManager的引用
        NotificationManager notificationManager = (NotificationManager)
            this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);   

        // 定义Notification的各种属性
        Notification notification =new Notification(R.drawable.icon,
                "督导系统", System.currentTimeMillis());
        //FLAG_AUTO_CANCEL   该通知能被状态栏的清除按钮给清除掉
        //FLAG_NO_CLEAR      该通知不能被状态栏的清除按钮给清除掉
        //FLAG_ONGOING_EVENT 通知放置在正在运行
        //FLAG_INSISTENT     是否一直进行,比如音乐一直播放,知道用户响应
        notification.flags |= Notification.FLAG_ONGOING_EVENT; // 将此通知放到通知栏的"Ongoing"即"正在运行"组中
        notification.flags |= Notification.FLAG_NO_CLEAR; // 表明在点击了通知栏中的"清除通知"后,此通知不清除,经常与FLAG_ONGOING_EVENT一起使用
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        //DEFAULT_ALL     使用所有默认值,比如声音,震动,闪屏等等
        //DEFAULT_LIGHTS  使用默认闪光提示
        //DEFAULT_SOUNDS  使用默认提示声音
        //DEFAULT_VIBRATE 使用默认手机震动,需加上<uses-permission android:name="android.permission.VIBRATE" />权限
        notification.defaults = Notification.DEFAULT_LIGHTS;
        //叠加效果常量
        //notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND;
        notification.ledARGB = Color.BLUE;
        notification.ledOnMS =5000; //闪光时间,毫秒

        // 设置通知的事件消息
        CharSequence contentTitle ="督导系统标题"; // 通知栏标题
        CharSequence contentText ="督导系统内容"; // 通知栏内容
        Intent notificationIntent =new Intent(MainActivity.this, MainActivity.class); // 点击该通知后要跳转的Activity
        PendingIntent contentItent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, contentTitle, contentText, contentItent);   

        // 把Notification传递给NotificationManager
        notificationManager.notify(0, notification);
    }
?
    //删除通知
    private void clearNotification(){
        // 启动后删除之前我们定义的通知
        NotificationManager notificationManager = (NotificationManager) this
                .getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel(0); 

}}

1. [代码][Java]代码

Android Notification通知详解

根据activity的生命周期,在activity不显示时,会执行onStop函数(比如按下home键),所以你在onStop函数(按退出键除外)里面把notification放在通知栏里,再此显示时,把notification从通知栏里去掉。或者,只要程序在运行就一直显示通知栏图标。

下面对Notification类中的一些常量,字段,方法简单介绍一下:
常量:
DEFAULT_ALL    使用所有默认值,比如声音,震动,闪屏等等
DEFAULT_LIGHTS 使用默认闪光提示
DEFAULT_SOUNDS 使用默认提示声音
DEFAULT_VIBRATE 使用默认手机震动
【说明】:加入手机震动,一定要在manifest.xml中加入权限:
<uses-permission android:name="android.permission.VIBRATE" />
以上的效果常量可以叠加,即通过
notification.defaults =DEFAULT_SOUND|DEFAULT_VIBRATE;
notification.defaults |= DEFAULT_SOUND (最好在真机上测试,震动效果模拟器上没有)

//设置flag位
FLAG_AUTO_CANCEL  该通知能被状态栏的清除按钮给清除掉
FLAG_NO_CLEAR     该通知能被状态栏的清除按钮给清除掉
FLAG_ONGOING_EVENT 通知放置在正在运行
FLAG_INSISTENT 是否一直进行,比如音乐一直播放,知道用户响应

常用字段:
contentIntent  设置PendingIntent对象,点击时发送该Intent
defaults 添加默认效果
flags 设置flag位,例如FLAG_NO_CLEAR等
icon 设置图标
sound 设置声音
tickerText 显示在状态栏中的文字
when 发送此通知的时间戳

NotificationManager常用方法介绍:
public void cancelAll() 移除所有通知(只是针对当前Context下的Notification)
public  void cancel(int id) 移除标记为id的通知 (只是针对当前Context下的所有Notification)
public  void notify(String tag ,int id, Notification notification) 将通知加入状态栏,标签为tag,标记为id
public  void notify(int id, Notification notification) 将通知加入状态栏,标记为id

Notifications

In this document

  1. Notification Display Elements

    1. Normal view
    2. Big view
  2. Creating a Notification
    1. Required notification contents
    2. Optional notification contents and settings
    3. Notification actions
    4. Creating a simple notification
    5. Applying a big view style to a notification
    6. Handling compatibility
  3. Managing Notifications
    1. Updating notifications
    2. Removing notifications
  4. Preserving Navigation when Starting an Activity
    1. Setting up a regular activity PendingIntent
    2. Setting up a special activity PendingIntent
  5. Displaying Progress in a Notification
    1. Displaying a fixed-duration progress indicator
    2. Displaying a continuing activity indicator
  6. Custom Notification Layouts

Key classes

  1. NotificationManager
  2. NotificationCompat

Videos

  1. Notifications in 4.1

See also

  1. Android Design: Notifications

A notification is a message you can display to the user outside of your application‘s normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification
area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.

Figure 1. Notifications in the notification area.

Figure 2. Notifications in the notification drawer.

Notification Design

Notifications, as an important part of the Android UI, have their own design guidelines. To learn how to design notifications and their interactions, read the Android Design Guide Notifications topic.

Note: Except where noted, this guide refers to the NotificationCompat.Builder class
in the version 4 Support Library. The class Notification.Builder was
added in Android 3.0.

Notification Display Elements



Notifications in the notification drawer can appear in one of two visual styles, depending on the version and the state of the drawer:

Normal view
The standard view of the notifications in the notification drawer.
Big view
A large view that‘s visible when the notification is expanded. Big view is part of the expanded notification feature available as of Android 4.1.

These styles are described in the following sections.

Normal view

A notification in normal view appears in an area that‘s up to 64 dp tall. Even if you create a notification with a big view style, it will appear in normal view until it‘s expanded. This
is an example of a normal view:

Figure 3. Notification in normal view.

The callouts in the illustration refer to the following:

  1. Content title
  2. Large icon
  3. Content text
  4. Content info
  5. Small icon
  6. Time that the notification was issued. You can set an explicit value with setWhen();
    if you don‘t it defaults to the time that the system received the notification.

Big view

A notification‘s big view appears only when the notification is expanded, which happens when the notification is at the top of the notification drawer, or when the user expands the notification
with a gesture. Expanded notifications are available starting with Android 4.1.

The following screenshot shows an inbox-style notification:

Figure 4. Big view notification.

Notice that the big view shares most of its visual elements with the normal view. The only difference is callout number 7, the details area. Each big view style sets this area in a different
way. The available styles are:

Big picture style
The details area contains a bitmap up to 256 dp tall in its detail section.
Big text style
Displays a large text block in the details section.
Inbox style
Displays lines of text in the details section.

All of the big view styles also have the following content options that aren‘t available in normal view:

Big content title
Allows you to override the normal view‘s content title with a title that appears only in the expanded view.
Summary text
Allows you to add a line of text below the details area.

Applying a big view style to a notification is described in the section Applying
a big view style to a notification.

Creating a Notification



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 Notification object
containing your specifications. To issue the notification, you pass the Notification object
to the system by calling NotificationManager.notify().

Required notification contents

Notification object must contain
the following:

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

Optional notification contents and settings

All other notification settings and contents are optional. To learn more about them, see the reference documentation for NotificationCompat.Builder.

Notification actions

Although they‘re optional, you should add at least one action to your notification. An action allows users to go directly from the notification to an Activity in
your application, where they can look at one or more events or do further work.

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. If you use additional action buttons, you must
also make their functionality available in an Activity in
your app; see the section Handling compatibility for more details.

Inside a Notification,
the action itself is defined by a PendingIntent containing
an Intent that
starts an Activity in
your application. To associate the PendingIntent with
a gesture, call the appropriate method of NotificationCompat.Builder.
For example, if you want to start Activity when
the user clicks the notification text in the notification drawer, you add the PendingIntent by
callingsetContentIntent().

Starting an Activity when
the user clicks the notification is the most common action scenario. You can also start an Activity when
the user dismisses a notification. In Android 4.1 and later, you can start an Activity from
an action button. To learn more, read the reference guide for NotificationCompat.Builder.

Creating a simple notification

The following snippet illustrates a simple notification that specifies an activity to open when the user clicks the notification. Notice that the code creates a TaskStackBuilder object
and uses it to create the PendingIntent for
the action. This pattern is explained in more detail in the section Preserving Navigation when Starting
an Activity:

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());

That‘s it. Your user has now been notified.

Applying a big view style to a notification

To have a notification appear in a big view when it‘s expanded, first create a NotificationCompat.Builder object
with the normal view options you want. Next, call Builder.setStyle() with
a big view style object as its argument.

Remember that expanded notifications are not available on platforms prior to Android 4.1. To learn how to handle notifications for Android 4.1 and for earlier platforms, read the section Handling
compatibility.

For example, the following code snippet demonstrates how to alter the notification created in the previous snippet to use the Inbox big view style:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)    .setSmallIcon(R.drawable.notification_icon)    .setContentTitle("Event tracker")    .setContentText("Events received")NotificationCompat.InboxStyle inboxStyle =        new NotificationCompat.InboxStyle();String[] events = new String[6];// Sets a title for the Inbox style big viewinboxStyle.setBigContentTitle("Event tracker details:");...// Moves events into the big viewfor (int i=0; i < events.length; i++) {

    inboxStyle.addLine(events[i]);}// Moves the big view style object into the notification object.mBuilder.setStyle(inBoxStyle);...// Issue the notification here.

Handling compatibility

Not all notification features are available for a particular version, even though the methods to set them are in the support library classNotificationCompat.Builder.
For example, action buttons, which depend on expanded notifications, only appear on Android 4.1 and higher, because expanded notifications themselves are only available on Android 4.1 and higher.

To ensure the best compatibility, create notifications with NotificationCompat and
its subclasses, particularly NotificationCompat.Builder.
In addition, follow this process when you implement a notification:

  1. Provide all of the notification‘s functionality to all users, regardless of the version they‘re using. To do this, verify that all of the functionality is available from an Activity in
    your app. You may want to add a new Activity to
    do this.

    For example, if you want to use addAction() to
    provide a control that stops and starts media playback, first implement this control in an Activity in
    your app.

  2. Ensure that all users can get to the functionality in the Activity,
    by having it start when users click the notification. To do this, create a PendingIntent for
    the Activity.
    Call setContentIntent() to
    add the PendingIntent to
    the notification.
  3. Now add the expanded notification features you want to use to the notification. Remember that any functionality you add also has to be available in the Activity that
    starts when users click the notification.

Managing Notifications



When you need to issue a notification multiple times for the same type of event, you should avoid making a completely new notification. Instead, you should consider updating a previous notification,
either by changing some of its values or by adding to it, or both.

For example, Gmail notifies the user that new emails have arrived by increasing its count of unread messages and by adding a summary of each email to the notification. This is called "stacking"
the notification; it‘s described in more detail in the Notifications Design guide.

Note: This Gmail feature requires the "inbox" big view style, which is part of the expanded notification feature available starting in Android
4.1.

The following section describes how to update notifications and also how to remove them.

Updating notifications

To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(ID,
notification)
. To update this notification once you‘ve issued it, update or create a NotificationCompat.Builder object,
build a Notification object
from it, and issue the Notification with
the same ID you used previously. If the previous notification is still visible, the system updates it from the contents of the Notification object.
If the previous notification has been dismissed, a new notification is created instead.

The following snippet demonstrates a notification that is updated to reflect the number of events that have occurred. It stacks the notification, showing a summary:

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());...

This produces a notification that looks like this:

Figure 5. Updated notification displayed in the notification drawer.

Removing notifications

Notifications remain visible until one of the following happens:

  • The user dismisses the notification either individually or by using "Clear All" (if the notification can be cleared).
  • The user clicks the notification, and you called setAutoCancel() when
    you created the notification.
  • You call cancel() for
    a specific notification ID. This method also deletes ongoing notifications.
  • You call cancelAll(),
    which removes all of the notifications you previously issued.

Preserving Navigation when Starting an Activity



When you start an Activity from
a notification, you must preserve the user‘s expected navigation experience. Clicking Back should take the user back through the application‘s normal work flow to the Home screen, and clicking Recents should
show the Activity as
a separate task. To preserve the navigation experience, you should start the Activity in
a fresh task. How you set up the PendingIntent to
give you a fresh task depends on the nature of the Activity you‘re
starting. There are two general situations:

Regular activity
You‘re starting an Activity that‘s
part of the application‘s normal workflow. In this situation, set up the PendingIntent to
start a fresh task, and provide the PendingIntent with
a back stack that reproduces the application‘s normal Back behavior.

Notifications from the Gmail app demonstrate this. When you click a notification for a single email message, you see the message itself. Touching Back takes
you backwards through Gmail to the Home screen, just as if you had entered Gmail from the Home screen rather than entering it from a notification.

This happens regardless of the application you were in when you touched the notification. For example, if you‘re in Gmail composing a message, and you click a notification for a single email,
you go immediately to that email. Touching Back takes you to the inbox and then the Home screen, rather than taking you to the message you were composing.

Special activity
The user only sees this Activity if
it‘s started from a notification. In a sense, the Activity extends
the notification by providing information that would be hard to display in the notification itself. For this situation, set up the PendingIntent to
start in a fresh task. There‘s no need to create a back stack, though, because the started Activity isn‘t
part of the application‘s activity flow. Clicking Back will still take the user to the Home screen.

Setting up a regular activity PendingIntent

To set up a PendingIntent that
starts a direct entry Activity,
follow these steps:

  1. Define your application‘s Activity hierarchy
    in the manifest.

    1. Add support for Android 4.0.3 and earlier. To do this, specify the parent of the Activity you‘re
      starting by adding a <meta-data> element
      as the child of the <activity>.

      For this element, set android:name="android.support.PARENT_ACTIVITY".
      Set android:value="<parent_activity_name>"where <parent_activity_name> is
      the value of android:name for
      the parent <activity> element.
      See the following XML for an example.

    2. Also add support for Android 4.1 and later. To do this, add the android:parentActivityName attribute
      to the <activity>element
      of the Activity you‘re
      starting.

    The final XML should look like this:

    <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>
  2. 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 the Activity.
      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 the Intent 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 calling TaskStackBuilder.editIntentAt().
      This is sometimes necessary to ensure that the target Activity displays
      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 this PendingIntent as
      the argument to setContentIntent().

The following code snippet demonstrates the process:

...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());

Setting up a special activity PendingIntent

The following section describes how to set up a special activity PendingIntent.

A special Activity doesn‘t
need a back stack, so you don‘t have to define its Activity hierarchy
in the manifest, and you don‘t have to call addParentStack() to
build a back stack. Instead, use the manifest to set up the Activity task
options, and create the PendingIntent by
calling getActivity():

  1. In your manifest, add the following attributes to the <activity> element
    for the Activity

    android:name="activityclass"
    The activity‘s fully-qualified class name.
    android:taskAffinity=""
    Combined with the FLAG_ACTIVITY_NEW_TASK flag
    that you set in code, this ensures that this Activity doesn‘t
    go into the application‘s default task. Any existing tasks that have the application‘s default affinity are not affected.
    android:excludeFromRecents="true"
    Excludes the new task from Recents, so that the user can‘t accidentally navigate back to it.

    This snippet shows the element:

    <activity    android:name=".ResultActivity"...    android:launchMode="singleTask"    android:taskAffinity=""    android:excludeFromRecents="true"></activity>...
  2. Build and issue the notification:
    1. Create an Intent that
      starts the Activity.
    2. Set the Activity to
      start in a new, empty task by calling setFlags() with
      the flags FLAG_ACTIVITY_NEW_TASK andFLAG_ACTIVITY_CLEAR_TASK.
    3. Set any other options you need for the Intent.
    4. Create a PendingIntent from
      the Intent by
      calling getActivity().
      You can then use this PendingIntent as
      the argument to setContentIntent().

    The following code snippet demonstrates the process:

    // Instantiate a Builder object.NotificationCompat.Builder builder = new NotificationCompat.Builder(this);// Creates an Intent for the ActivityIntent notifyIntent =        new Intent(new ComponentName(this, ResultActivity.class));// Sets the Activity to start in a new, empty tasknotifyIntent.setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK);// Creates the PendingIntentPendingIntent notifyIntent =        PendingIntent.getActivity(        this,        0,        notifyIntent        PendingIntent.FLAG_UPDATE_CURRENT);
    
    // Puts the PendingIntent into the notification builderbuilder.setContentIntent(notifyIntent);// 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());

Displaying Progress in a Notification



Notifications can include an animated progress indicator that shows users the status of an ongoing operation. If you can estimate how long the operation takes and how much of it is complete
at any time, use the "determinate" form of the indicator (a progress bar). If you can‘t estimate the length of the operation, use the "indeterminate" form of the indicator (an activity indicator).

Progress indicators are displayed with the platform‘s implementation of the ProgressBar class.

To use a progress indicator on platforms starting with Android 4.0, call setProgress().
For previous versions, you must create your own custom notification layout that includes a ProgressBar view.

The following sections describe how to display progress in a notification using setProgress().

Displaying a fixed-duration progress indicator

To display a determinate progress bar, add the bar to your notification by calling setProgress()
setProgress(max, progress, false)
 and then issue the notification. As your operation proceeds, increment progress,
and update the notification. At the end of the operation, progress should equal max.
A common way to call setProgress() is
to set max to 100 and then increment progress as
a "percent complete" value for the operation.

You can either leave the progress bar showing when the operation is done, or remove it. In either case, remember to update the notification text to show that the operation is complete. To
remove the progress bar, call setProgress()
setProgress(0, 0, false)
. For example:

...mNotifyManager =        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mBuilder = new NotificationCompat.Builder(this);mBuilder.setContentTitle("Picture Download")    .setContentText("Download in progress")    .setSmallIcon(R.drawable.ic_notification);// Start a lengthy operation in a background threadnew Thread(    new Runnable() {        @Override        public void run() {            int incr;            // Do the "lengthy" operation 20 times            for (incr = 0; incr <= 100; incr+=5) {                    // Sets the progress indicator to a max value, the                    // current completion percentage, and "determinate"                    // state                    mBuilder.setProgress(100, incr, false);                    // Displays the progress bar for the first time.                    mNotifyManager.notify(0, mBuilder.build());                        // Sleeps the thread, simulating an operation                        // that takes time                        try {                            // Sleep for 5 seconds                            Thread.sleep(5*1000);                        } catch (InterruptedException e) {                            Log.d(TAG, "sleep failure");                        }            }            // When the loop is finished, updates the notification            mBuilder.setContentText("Download complete")            // Removes the progress bar                    .setProgress(0,0,false);            mNotifyManager.notify(ID, mBuilder.build());        }    }// Starts the thread by calling the run() method in its Runnable).start();

The resulting notifications are shown in figure 6. On the left side is a snapshot of the notification during the operation; on the right side is a snapshot of it after the operation has
finished.

Figure 6. The progress bar during and after the operation.

Displaying a continuing activity indicator

To display an indeterminate activity indicator, add it to your notification with setProgress(0,
0, true)
 (the first two arguments are ignored), and issue the notification. The result is an indicator that has the same style as a progress bar, except that its animation is ongoing.

Issue the notification at the beginning of the operation. The animation will run until you modify your notification. When the operation is done, call setProgress()
setProgress(0, 0, false)
 and then update the notification to remove the activity indicator. Always do this; otherwise, the animation will run even when the operation is complete. Also remember to change the notification text to indicate that the
operation is complete.

To see how activity indicators work, refer to the preceding snippet. Locate the following lines:

// Sets the progress indicator to a max value, the current completion// percentage, and "determinate" statemBuilder.setProgress(100, incr, false);// Issues the notificationmNotifyManager.notify(0, mBuilder.build());

Replace the lines you‘ve found with the following lines:

 // Sets an activity indicator for an operation of indeterminate lengthmBuilder.setProgress(0, 0, true);// Issues the notificationmNotifyManager.notify(0, mBuilder.build());

The resulting indicator is shown in figure 7:

Figure 7. An ongoing activity indicator.

Custom Notification Layouts



The notifications framework allows you to define a custom notification layout, which defines the notification‘s appearance in a RemoteViews object.
Custom layout notifications are similar to normal notifications, but they‘re based on a RemoteViews defined
in a XML layout file.

The height available for a custom notification layout depends on the notification view. Normal view layouts are limited to 64 dp, and expanded view layouts are limited to 256 dp.

To define a custom notification layout, start by instantiating a RemoteViews object
that inflates an XML layout file. Then, instead of calling methods such as setContentTitle(),
call setContent().
To set content details in the custom notification, use the methods inRemoteViews to
set the values of the view‘s children:

  1. Create an XML layout for the notification in a separate file. You can use any file name you wish, but you must use the extension .xml
  2. In your app, use RemoteViews methods
    to define your notification‘s icons and text. Put this RemoteViews object
    into yourNotificationCompat.Builder by
    calling setContent().
    Avoid setting a background Drawable on
    your RemoteViews object,
    because your text color may become unreadable.

The RemoteViews class
also includes methods that you can use to easily add a Chronometer or ProgressBar to
your notification‘s layout. For more information about creating custom layouts for your notification, refer to the RemoteViews reference
documentation.

Caution: When you use a custom notification layout, take special care to ensure that your custom layout works with different device orientations
and resolutions. While this advice applies to all View layouts, it‘s especially important for notifications because the space in the notification drawer is very restricted. Don‘t make your custom layout too complex, and be sure to test it in various configurations.

Using style resources for custom notification text

Always use style resources for the text of a custom notification. The background color of the notification can vary across different devices and versions, and using style resources helps
you account for this. Starting in Android 2.3, the system defined a style for the standard notification layout text. If you use the same style in applications that target Android 2.3 or higher, you‘ll ensure that your text is visible against the display background.

Android Notification通知详解

时间: 2024-10-10 15:08:33

Android Notification通知详解的相关文章

Android基础入门教程——2.5.2 Notification(状态栏通知)详解

Android基础入门教程--2.5.2 Notification(状态栏通知)详解 标签(空格分隔): Android基础入门教程 本节引言: 本节带来的是Android中用于在状态栏显示通知信息的控件:Notification,相信大部分 学Android都对他都很熟悉,而网上很多关于Notification的使用教程都是基于2.x的,而 现在普遍的Android设备基本都在4.x以上,甚至是5.0以上的都有:他们各自的Notification 都是不一样的!而本节给大家讲解的是基于4.x以

Xamarin.Android通知详解

一.发送通知的机制 在日常的app应用中经常需要使用通知,因为服务.广播后台活动如果有事件需要通知用户,则需要通过通知栏显示,而在Xamarin.Android下的通知需要获取NotificationManager服务,而该服务需要通过GetSystemService获取,同时还要传递一个标识符.获取了通知管理器后我们就可以实例化Notification,然后再由NotificationManager发送出去.这就是整个过程了.下面我们将一一详解通知. 二.前期准备 为了下面的学习和演示我们需要

Android Service使用详解

Service是Android系统中的四大组件之一,主要有两个应用场景:后台运行和跨进程访问.Service可以在后台执行长时间运行操作而不提供用户界面,除非系统必须回收内存资源,否则系统不会停止或销毁服务.服务可由其他应用组件启动,而且即使用户切换到其他应用,服务仍将在后台继续运行. 此外,组件可以绑定到服务,以与之进行交互,甚至是执行进程间通信 (IPC) 需要注意的是,Service是在主线程里执行操作的,可能会因为执行耗时操作而导致ANR 一.基础知识 Service可以分为以下三种形式

Android 四大组件 详解

[置顶] Android四大组件详解 分类: Android四大组件2013-02-09 16:23 19411人阅读 评论(13) 收藏 举报 Android开发 注:本文主要来自网易的一个博主的文章,经过阅读,总结,故留下文章在此 Android四大基本组件介绍与生命周期 Android四大基本组件分别是Activity,Service服务,Content Provider内容提供者,BroadcastReceiver广播接收器. 一:了解四大基本组件 Activity : 应用程序中,一个

Android之canvas详解

首先说一下canvas类: Class Overview The Canvas class holds the "draw" calls. To draw something, you need 4 basic components: A Bitmap to hold the pixels, a Canvas to host the draw calls (writing into the bitmap), a drawing primitive (e.g. Rect, Path, t

ios开发——实用技术OC-Swift篇&amp;本地通知与远程通知详解

本地通知与远程通知详解 一:本地通知 Local Notification的作用 Local Notification(本地通知) :是根据本机状态做出的通知行为,因此,凡是仅需依赖本机状态即可判断需要发出通知的行为都可以或者说应该使用Local Notification来处理.比方说:iBeacon中进入了某个Beacon region,或者说自定义的一些定时提醒等. 构建Local Notification 在iOS中,构建LocalNotification非常简单,只需要掌握好NSLoca

android源码分析 android toast使用详解 toast自定义

在安卓开发过程中,toast使我们经常使用的一个类,当我们需要向用户传达一些信息,但是不需要和用户交互时,该方式就是一种十分恰当的途径. 我们习惯了这样使用toast:Toast.makeText(Context context, String info, int duration).show();该方法是 系统为我们提供的一个方便的创建toast对象的静态方法,其内部依然是调用toast的相关方法完成.下面 就从其源码对该类的实现做一个分析 在toast类中,最重要的用于显示该toast的sh

Android进阶——Preference详解之Preference系的基本应用和管理(二)

引言 前面一篇文章Android进阶--Preference详解之初识Preference及Preference系(一)简单描述下了Preference的家族构成和基本知识,相信对于Preference早已不会陌生,肯定也跃跃欲试了吧,这篇文章就给大家总结下Preference.PreferenceActivity.PreferenceGroup.RingtonePreference的普通应用和管理,还有通过一些测试来验证一些机制和原理. 一.PreferenceActivity 1.Prefe

Android WebView 开发详解

Android WebView 开发详解 1.概览: Android WebView 做为承载网页的载体控件,他在网页显示的过程中会产生一些事件,并回调给我们的应用程序,以便我们在网页加载过程中做应用程序想处理的事情.比如说客户端需要显示网页加载的进度.网页加载发生错误等等事件. WebView提供两个事件回调类给应用层,分别为WebViewClient,WebChromeClient开发者可以继承这两个类,接手相应事件处理.WebViewClient 主要提供网页加载各个阶段的通知,比如网页开