Android之 Notification 的多种用法--带你了解通知栏的用法

我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的。

我们也知道Android系统也是在不断升级的,有关Notification的用法也就有很多种,有的方法已经被android抛弃了,现在我实现了三种不同的方法,并适应不同的android版本。现在我就把代码公布出来,我喜欢把解释写在代码中,在这里我就不多说了,先看效果图:

主要的代码如下:


package net.loonggg.notification;

 

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.RemoteViews;

 

public class MainActivity extends Activity {

	private static final int NOTIFICATION_FLAG = 1;

 

	@Override

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

	}

 

	public void notificationMethod(View view) {

		// 在Android进行通知处理,首先需要重系统哪里获得通知管理器NotificationManager,它是一个系统Service。

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

		switch (view.getId()) {

		// 默认通知

		case R.id.btn1:

			// 创建一个PendingIntent,和Intent类似,不同的是由于不是马上调用,需要在下拉状态条出发的activity,所以采用的是PendingIntent,即点击Notification跳转启动到哪个Activity

			PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,

					new Intent(this, MainActivity.class), 0);

			// 下面需兼容Android 2.x版本是的处理方式

			// Notification notify1 = new Notification(R.drawable.message,

			// "TickerText:" + "您有新短消息,请注意查收!", System.currentTimeMillis());

			Notification notify1 = new Notification();

			notify1.icon = R.drawable.message;

			notify1.tickerText = "TickerText:您有新短消息,请注意查收!";

			notify1.when = System.currentTimeMillis();

			notify1.setLatestEventInfo(this, "Notification Title",

					"This is the notification message", pendingIntent);

			notify1.number = 1;

			notify1.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。

			// 通过通知管理器来发起通知。如果id不同,则每click,在statu那里增加一个提示

			manager.notify(NOTIFICATION_FLAG, notify1);

			break;

		// 默认通知 API11及之后可用

		case R.id.btn2:

			PendingIntent pendingIntent2 = PendingIntent.getActivity(this, 0,

					new Intent(this, MainActivity.class), 0);

			// 通过Notification.Builder来创建通知,注意API Level

			// API11之后才支持

			Notification notify2 = new Notification.Builder(this)

					.setSmallIcon(R.drawable.message) // 设置状态栏中的小图片,尺寸一般建议在24×24,这个图片同样也是在下拉状态栏中所显示,如果在那里需要更换更大的图片,可以使用setLargeIcon(Bitmap

														// icon)

					.setTicker("TickerText:" + "您有新短消息,请注意查收!")// 设置在status

																// bar上显示的提示文字

					.setContentTitle("Notification Title")// 设置在下拉status

															// bar后Activity,本例子中的NotififyMessage的TextView中显示的标题

					.setContentText("This is the notification message")// TextView中显示的详细内容

					.setContentIntent(pendingIntent2) // 关联PendingIntent

					.setNumber(1) // 在TextView的右方显示的数字,可放大图片看,在最右侧。这个number同时也起到一个序列号的左右,如果多个触发多个通知(同一ID),可以指定显示哪一个。

					.getNotification(); // 需要注意build()是在API level

			// 16及之后增加的,在API11中可以使用getNotificatin()来代替

			notify2.flags |= Notification.FLAG_AUTO_CANCEL;

			manager.notify(NOTIFICATION_FLAG, notify2);

			break;

		// 默认通知 API16及之后可用

		case R.id.btn3:

			PendingIntent pendingIntent3 = PendingIntent.getActivity(this, 0,

					new Intent(this, MainActivity.class), 0);

			// 通过Notification.Builder来创建通知,注意API Level

			// API16之后才支持

			Notification notify3 = new Notification.Builder(this)

					.setSmallIcon(R.drawable.message)

					.setTicker("TickerText:" + "您有新短消息,请注意查收!")

					.setContentTitle("Notification Title")

					.setContentText("This is the notification message")

					.setContentIntent(pendingIntent3).setNumber(1).build(); // 需要注意build()是在API

																			// level16及之后增加的,API11可以使用getNotificatin()来替代

			notify3.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。

			manager.notify(NOTIFICATION_FLAG, notify3);// 步骤4:通过通知管理器来发起通知。如果id不同,则每click,在status哪里增加一个提示

			break;

		// 自定义通知

		case R.id.btn4:

			// Notification myNotify = new Notification(R.drawable.message,

			// "自定义通知:您有新短信息了,请注意查收!", System.currentTimeMillis());

			Notification myNotify = new Notification();

			myNotify.icon = R.drawable.message;

			myNotify.tickerText = "TickerText:您有新短消息,请注意查收!";

			myNotify.when = System.currentTimeMillis();

			myNotify.flags = Notification.FLAG_NO_CLEAR;// 不能够自动清除

			RemoteViews rv = new RemoteViews(getPackageName(),

					R.layout.my_notification);

			rv.setTextViewText(R.id.text_content, "hello wrold!");

			myNotify.contentView = rv;

			Intent intent = new Intent(Intent.ACTION_MAIN);

			PendingIntent contentIntent = PendingIntent.getActivity(this, 1,

					intent, 1);

			myNotify.contentIntent = contentIntent;

			manager.notify(NOTIFICATION_FLAG, myNotify);

			break;

		case R.id.btn5:

			// 清除id为NOTIFICATION_FLAG的通知

			manager.cancel(NOTIFICATION_FLAG);

			// 清除所有的通知

			// manager.cancelAll();

			break;

		default:

			break;

		}

	}

}

再看主布局文件:


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

    android:orientation="vertical"

    tools:context=".MainActivity" >

 

    <Button

        android:id="@+id/btn1"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:onClick="notificationMethod"

        android:text="默认通知(已被抛弃,但是通用)" />

 

    <Button

        android:id="@+id/btn2"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:onClick="notificationMethod"

        android:text="默认通知(API11之后可用)" />

 

    <Button

        android:id="@+id/btn3"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:onClick="notificationMethod"

        android:text="默认通知(API16之后可用)" />

 

    <Button

        android:id="@+id/btn4"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:onClick="notificationMethod"

        android:text="自定义通知" />

 

    <Button

        android:id="@+id/btn5"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:onClick="notificationMethod"

        android:text="清除通知" />

 

</LinearLayout>

还有一个是:自定义通知的布局文件my_notification.xml,代码如下:


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:background="#ffffff"

    android:orientation="vertical" >

 

    <TextView

        android:id="@+id/text_content"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textSize="20sp" />

 

</LinearLayout>

Notification

  Notification,俗称通知,是一种具有全局效果的通知,它展示在屏幕的顶端,首先会表现为一个图标的形式,当用户向下滑动的时候,展示出通知具体的内容。

  注意:因为一些Android版本的兼容性问题,对于Notification而言,Android3.0是一个分水岭,在其之前构建Notification推荐使用Notification.Builder构建,而在Android3.0之后,一般推荐使用NotificationCompat.Builder构建。本文的所有代码环境均在4.3中完成,如果使用4.1一下的设备测试,请注意兼容性问题。

  通知一般通过NotificationManager服务来发送一个Notification对象来完成,NotificationManager是一个重要的系统级服务,该对象位于应用程序的框架层中,应用程序可以通过它像系统发送全局的通知。这个时候需要创建一个Notification对象,用于承载通知的内容。但是一般在实际使用过程中,一般不会直接构建Notification对象,而是使用它的一个内部类NotificationCompat.Builder来实例化一个对象(Android3.0之下使用Notification.Builder),并设置通知的各种属性,最后通过NotificationCompat.Builder.build()方法得到一个Notification对象。当获得这个对象之后,可以使用NotificationManager.notify()方法发送通知。

  NotificationManager类是一个通知管理器类,这个对象是由系统维护的服务,是以单例模式获得,所以一般并不直接实例化这个对象。在Activity中,可以使用Activity.getSystemService(String)方法获取NotificationManager对象,Activity.getSystemService(String)方法可以通过Android系统级服务的句柄,返回对应的对象。在这里需要返回NotificationManager,所以直接传递Context.NOTIFICATION_SERVICE即可。

  虽然通知中提供了各种属性的设置,但是一个通知对象,有几个属性是必须要设置的,其他的属性均是可选的,必须设置的属性如下:

?小图标,使用setSamllIcon()方法设置。

?标题,使用setContentTitle()方法设置。

?文本内容,使用setContentText()方法设置。

更新与移除通知

  在使用NotificationManager.notify()发送通知的时候,需要传递一个标识符,用于唯一标识这个通知。对于有些场景,并不是无限的添加新的通知,有时候需要更新原有通知的信息,这个时候可以重写构建Notification,而使用与之前通知相同标识符来发送通知,这个时候旧的通知就被被新的通知所取代,起到更新通知的效果。

  对于一个通知,当展示在状态栏之后,但是使用过后,如何取消呢?Android为我们提供两种方式移除通知,一种是Notification自己维护,使用setAutoCancel()方法设置是否维护,传递一个boolean类型的数据。另外一种方式使用NotificationManager通知管理器对象来维护,它通过notify()发送通知的时候,指定的通知标识Id来操作通知,可以使用cancel(int)来移除一个指定的通知,也可以使用cancelAll()移除所有的通知。

  使用NotificationManager移除指定通知示例:

?


1

2

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

mNotificationManager.cancel(0);

PendingIntent

  对于一个通知而言,它显示的消息是有限的,一般仅用于提示一些概要信息。但是一般简短的消息,并不能表达需要告诉用户的全部内容,所以需要绑定一个意图,当用户点击通知的时候,调用一个意图展示出一个Activity用来显示详细的内容。而Notification中,并不使用常规的Intent去传递一个意图,而是使用PendingIntent。

  先来聊聊Intent和PendingIntent的区别,PendingIntent可以看做是对Intent的包装,通过名称可以看出PendingIntent用于处理即将发生的意图,而Intent用来处理马上发生的意图。而对于通知来说,它是一个系统级的全局的通知,并不确定这个意图被执行的时间。当在应用外部执行PendingIntent时,因为它保存了触发App的Context,使得外部App可以如果当前App一样执行PendingIntent里的Intent,就算执行时触发通知的App已经不存在了,也能通过存在PendingIntent里的Context照常执行Intent,并且还可以处理Intent所带来的额外的信息。

  PendingIntent提供了多个静态的getXxx()方法,用于获得适用于不同场景的PendingIntent对象。一般需要传递的几个参数都很常规,只介绍一个flag参数,用于标识PendingIntent的构造选择:

?FLAG_CANCEL_CURRENT:如果构建的PendingIntent已经存在,则取消前一个,重新构建一个。

?FLAG_NO_CREATE:如果前一个PendingIntent已经不存在了,将不再构建它。

?FLAG_ONE_SHOT:表明这里构建的PendingIntent只能使用一次。

?FLAG_UPDATE_CURRENT:如果构建的PendingIntent已经存在,则替换它,常用。

Notification视觉风格

  Notification有两种视觉风格,一种是标准视图(Normal view)、一种是大视图(Big view)。标准视图在Android中各版本是通用的,但是对于大视图而言,仅支持Android4.1+的版本。

  从官方文档了解到,一个标准视图显示的大小要保持在64dp高,宽度为屏幕标准。标准视图的通知主体内容有一下几个:

    通知标题。大图标。通知内容。通知消息。小图标。通知的时间,一般为系统时间,也可以使用setWhen()设置。

      下面通过一个示例,模仿上面效果的通知。

    btnNotification.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

    Bitmap btm = BitmapFactory.decodeResource(getResources(),

    R.drawable.msg);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(

    MainActivity.this).setSmallIcon(R.drawable.msg)

    .setContentTitle("5 new message")

    .setContentText("[email protected]");

    mBuilder.setTicker("New message");//第一次提示消息的时候显示在通知栏上

    mBuilder.setNumber(12);

    mBuilder.setLargeIcon(btm);

    mBuilder.setAutoCancel(true);//自己维护通知的消失

    //构建一个Intent

    Intent resultIntent = new Intent(MainActivity.this,

    ResultActivity.class);

    //封装一个Intent

    PendingIntent resultPendingIntent = PendingIntent.getActivity(

    MainActivity.this, 0, resultIntent,

    PendingIntent.FLAG_UPDATE_CURRENT);

    // 设置通知主题的意图

    mBuilder.setContentIntent(resultPendingIntent);

    //获取通知管理器对象

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

    mNotificationManager.notify(0, mBuilder.build());

    }

    }); 复制代码

      显示效果:

      而对于大视图(Big View)而言,它的细节区域只能显示256dp高度的内容,并且只对Android4.1+之后的设备才支持,它比标准视图不一样的地方,均需要使用setStyle()方法设定,它大致的效果如下:

      setStyle()传递一个NotificationCompat.Style对象,它是一个抽象类,Android为我们提供了三个实现类,用于显示不同的场景。分别是:

    NotificationCompat.BigPictureStyle, 在细节部分显示一个256dp高度的位图。NotificationCompat.BigTextStyle,在细节部分显示一个大的文本块。NotificationCompat.InboxStyle,在细节部分显示一段行文本。

      如果仅仅显示一个图片,使用BigPictureStyle是最方便的;如果需要显示一个富文本信息,则可以使用BigTextStyle;如果仅仅用于显示一个文本的信息,那么使用InboxStyle即可。后面会以一个示例来展示InboxStyle的使用,模仿上面图片的显示。

      实现代码:

    ?


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    btnBigViewNotification.setOnClickListener(new

    View.OnClickListener() {

    @Override

    public

    void

    onClick(View v) {

    Bitmap
    btm = BitmapFactory.decodeResource(getResources(),

    R.drawable.msg);

    Intent
    intent =
    new

    Intent(MainActivity.
    this,

    ResultActivity.class);

    PendingIntent
    pendingIntent = PendingIntent.getActivity(

    MainActivity.this,
    0,
    intent,

    PendingIntent.FLAG_CANCEL_CURRENT);

    Notification
    noti =
    new

    NotificationCompat.Builder(

    MainActivity.this)

    .setSmallIcon(R.drawable.msg)

    .setLargeIcon(btm)

    .setNumber(13)

    .setContentIntent(pendingIntent)

    .setStyle(

    new

    NotificationCompat.InboxStyle()

    .addLine(

    "M.Twain
    (Google+) Haiku is more than a cert..."
    )

    .addLine("M.Twain
    Reminder"
    )

    .addLine("M.Twain
    Lunch?"
    )

    .addLine("M.Twain
    Revised Specs"
    )

    .addLine("M.Twain
    "
    )

    .addLine(

    "Google
    Play Celebrate 25 billion apps with Goo.."
    )

    .addLine(

    "Stack
    Exchange StackOverflow weekly Newsl..."
    )

    .setBigContentTitle("6
    new message"
    )

    .setSummaryText("[email protected]"))

    .build();

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

    mNotificationManager.notify(0,
    noti);

    }

    });

      展示效果:

    进度条样式的通知<&#26;喎?"http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vc3Ryb25nPjxicj4KPGJyPgqhoaGhttTT2tK7uPax6te8zajWqqOs09DKsbryz9TKvrXEz/vPorKisrvSu7aoyse+ssystcSjrLu5v8nS1MnotqjSu7j2vfi2yMz108PT2s/Uyr7Kws7xzeqzybXEvfi2yKGjPGJyPgo8YnI+CqGhoaFOb3RpZmljYXRpb24uQnVpbGRlcsDg1tDM4bmp0ru49nNldFByb2dyZXNzKGludCBtYXgsaW50IHByb2dyZXNzLGJvb2xlYW4gaW5kZXRlcm1pbmF0ZSm3vbeo08PT2sno1sO9+LbIzPWjrG1heNPD09rJ6Laovfi2yLXE1+6088r9o6xwcm9ncmVzc9PD09rJ6LaotbHHsLXEvfi2yKOsaW5kZXRlcm1pbmF0ZdPD09rKx7fxysfSu7j2yLe2qL34tsjWu7XEvfi2yMz1oaPNqLn9aW5kZXRlcm1pbmF0ZbXEyejWw6Osv8nS1Mq1z9bBvdbWsrvNrNH5yr21xL34tsjM9aOs0rvW1srH09C9+LbItcSjqGZhbHNlo6ks0rvW1srH0a27t8H3tq+1xKOoZmFsc2WjqaGjz8LD5rfWsfDTw8G9uPbKvsD90d3KvqO6PGJyPgo8YnI+CqGhoaHT0L34tsi1xL34tsjM9aOsyrXP1rT6wuujuiA8YnI+Cjxicj4KPHByZSBjbGFzcz0="brush:java;">
    btnProgreNotification.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); builder = new NotificationCompat.Builder(MainActivity.this) .setSmallIcon(R.drawable.ic_launcher)
    .setContentTitle("Picture Download") .setContentText("Download in progress"); builder.setAutoCancel(true); //通过一个子线程,动态增加进度条刻度 new Thread(new Runnable() { @Override public void run() { int incr; for (incr = 0; incr <= 100; incr += 5) { builder.setProgress(100,
    incr, false); manager.notify(0, builder.build()); try { Thread.sleep(300); } catch (InterruptedException e) { Log.i(TAG, "sleep failure"); } } builder.setContentText("Download complete") .setProgress(0, 0, false); manager.notify(0, builder.build()); } }).start();
    } });

      显示效果:

      对于循环流动的进度条,下面是实现代码:

    ?


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    btnProNotification.setOnClickListener(new

    View.OnClickListener() {

    @Override

    public

    void

    onClick(View v) {

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

    builder
    =
    new

    NotificationCompat.Builder(MainActivity.
    this)

    .setSmallIcon(R.drawable.ic_launcher)

    .setContentTitle("Picture
    Download"
    )

    .setContentText("Download
    in progress"
    );

    builder.setProgress(0,
    0,
    true);//设置为true,表示流动

    manager.notify(0,
    builder.build());

    //5秒之后还停止流动

    new

    Thread(
    new

    Runnable() {

    @Override

    public

    void

    run() {

    try

    {

    Thread.sleep(5000);

    }
    catch

    (InterruptedException e) {

    e.printStackTrace();

    }

    builder.setProgress(100,
    100,
    false);//设置为true,表示刻度

    manager.notify(0,
    builder.build());

    }

    }).start();

    }

    });

      效果展示:

    自定义通知

      和Toast一样,通知也可以使用自定义的XML来自定义样式,但是对于通知而言,因为它的全局性,并不能简单的通过inflate膨胀出一个View,因为可能触发通知的时候,响应的App已经关闭,无法获取当指定的XML布局文件。所以需要使用单独的一个RemoteViews类来操作。

      RemoteViews,描述了一个视图层次的结构,可以显示在另一个进程。层次结构也是从布局文件中“膨胀”出一个视图,这个类,提供了一些基本的操作求改其膨胀的内容。

      RemoteViews提供了多个构造函数,一般使用RemoteViews(String packageName,int layoutId)。第一个参数为包的名称,第二个为layout资源的Id。当获取到RemoteViews对象之后,可以使用它的一系列setXxx()方法通过控件的Id设置控件的属性。最后使用NotificationCompat.Builder.setContent(RemoteViews)方法设置它到一个Notification中。

      下面通过一个示例展示它:

      自定义的布局XML代码:

    ?


    1

    2

    3

    4

    <relativelayout
    android:layout_width=
    "match_parent"

    android:layout_height=
    "match_parent"

    android:padding=
    "10dp">

    <imageview
    android:id=
    "@+id/imageNo"

    android:layout_width=
    "wrap_content"

    android:layout_height=
    "match_parent"

    android:layout_alignparentleft=
    "true"

    android:layout_marginright=
    "10dp">

    <textview
    android:id=
    "@+id/titleNo"

    android:layout_width=
    "wrap_content"

    android:layout_height=
    "wrap_content"

    android:layout_torightof=
    "@id/imageNo">

    <textview
    android:id=
    "@+id/textNo"

    android:layout_width=
    "wrap_content"

    android:layout_height=
    "wrap_content"

    android:layout_below=
    "@id/titleNo"

    android:layout_torightof=
    "@id/imageNo"></textview></textview></imageview></relativelayout>

    实现代码:

    ?


    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    btnCustomNotification.setOnClickListener(new

    View.OnClickListener() {

    @Override

    public

    void

    onClick(View v) {

    RemoteViews
    contentViews =
    new

    RemoteViews(getPackageName(),

    R.layout.custom_notification);

    //通过控件的Id设置属性

    contentViews

    .setImageViewResource(R.id.imageNo,
    R.drawable.btm1);

    contentViews.setTextViewText(R.id.titleNo,
    "自定义通知标题");

    contentViews.setTextViewText(R.id.textNo,
    "自定义通知内容");

    Intent
    intent =
    new

    Intent(MainActivity.
    this,

    ResultActivity.class);

    PendingIntent
    pendingIntent = PendingIntent.getActivity(

    MainActivity.this,
    0,
    intent,

    PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder
    mBuilder =
    new

    NotificationCompat.Builder(

    MainActivity.this).setSmallIcon(R.drawable.ic_launcher)

    .setContentTitle("My
    notification"
    )

    .setTicker("new
    message"
    );

    mBuilder.setAutoCancel(true);

    mBuilder.setContentIntent(pendingIntent);

    mBuilder.setContent(contentViews);

    mBuilder.setAutoCancel(true);

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

    mNotificationManager.notify(10,
    mBuilder.build());

    }

    });

      效果展示:

    设定提示响应

      对于有些通知,需要调用一些设备的资源,使用户能更快的发现有新通知,一般可设定的响应有:铃声、闪光灯、震动。对于这三个属性,NotificationCompat.Builder提供了三个方法设定:

    setSound(Uri sound):设定一个铃声,用于在通知的时候响应。传递一个Uri的参数,格式为“file:///mnt/sdcard/Xxx.mp3”。setLights(

    int argb, int onMs, int offMs

    ):设定前置LED灯的闪烁速率,持续毫秒数,停顿毫秒数。setVibrate(long[] pattern):设定震动的模式,以一个long数组保存毫秒级间隔的震动。

      大多数时候,我们并不需要设定一个特定的响应效果,只需要遵照用户设备上系统通知的效果即可,那么可以使用setDefaults(int)方法设定默认响应参数,在Notification中,对它的参数使用常量定义了,我们只需使用即可:

    DEFAULT_ALL:铃声、闪光、震动均系统默认。DEFAULT_SOUND:系统默认铃声。DEFAULT_VIBRATE:系统默认震动。DEFAULT_LIGHTS:系统默认闪光。

      而在Android中,如果需要访问硬件设备的话,是需要对其进行授权的,所以需要在清单文件AndroidManifest.xml中增加两个授权,分别授予访问振动器与闪光灯的权限:

    ?


    1

    2

    3

    4

    <!--
    闪光灯权限 -->

    <uses-permission
    android:name=
    "android.permission.FLASHLIGHT">

    <!--
    振动器权限 -->

    <uses-permission
    android:name=
    "android.permission.VIBRATE"></uses-permission></uses-permission>

      因为只是一个属性的设定,并且大部分时候,使用系统设定即可,这里就不提供代码示例了。

    总结

      通知算是Android中比较常用的一个功能,可以保持自己App的长存,在用户没有进入App的时候,也提供了与用户交互的可能。

时间: 2024-12-10 01:12:21

Android之 Notification 的多种用法--带你了解通知栏的用法的相关文章

Android之Notification的多种用法

[置顶] Android之Notification的多种用法 标签: notification 2013-12-27 18:18 59635人阅读 评论(16) 收藏 举报  分类: android编程笔记(46)  版权声明:本文为博主原创文章,未经博主允许不得转载. 我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的. 我们也知道Android系统也是在

Android之Notification的多种用法(转)

我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的. 我们也知道Android系统也是在不断升级的,有关Notification的用法也就有很多种,有的方法已经被android抛弃了,现在我实现了三种不同的方法,并适应不同的android版本.现在我就把代码公布出来,我喜欢把解释写在代码中,在这里我就不多说了,先看效果图: package net.loong

Android关于notification的在不同API下的用法说明

当我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的. 我们也知道Android系统也是在不断升级的,有关Notification的用法也就有很多种,有的方法已经被android抛弃了,现在我实现了三种不同的方法,并适应不同的android版本.现在我就把代码公布出来,我喜欢把解释写在代码中,在这里我就不多说了,先看效果图: 再看代码,主要的代码如下: <s

android通知-Notification

android中,当app需要向发送一些通知,让使用者注意到你想要告知的信息时,可以用Notification.下面,就来讨论一下,Notification的用法,我们从实际的小例子来进行学习. 1.新建一个项目,在layout布局里写两个按钮,一个用来开启通知,一个用来关闭通知.下面直接上布局代码. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=&qu

Android Volley完全解析(四),带你从源码的角度理解Volley

转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/17656437 经过前三篇文章的学习,Volley的用法我们已经掌握的差不多了,但是对于Volley的工作原理,恐怕有很多朋友还不是很清楚.因此,本篇文章中我们就来一起阅读一下Volley的源码,将它的工作流程整体地梳理一遍.同时,这也是Volley系列的最后一篇文章了. 其实,Volley的官方文档中本身就附有了一张Volley的工作流程图,如下图所示. 多数朋友突然看到一张这样

Android基础入门教程——7.5.1 WebView(网页视图)基本用法

Android基础入门教程--7.5.1 WebView(网页视图)基本用法 标签(空格分隔): Android基础入门教程 本节引言 本节给大家带来的是Android中的一个用于显示网页的控件:WebView(网页视图),现在Android应用 层开发的方向有两种:客户端开发和HTML5移动端开发!所谓的HTML5端就是:HTML5 + CSS + JS来构建 一个网页版的应用,而这中间的媒介就是这个WebView,而Web和网页端可以通过JS来进行交互,比如, 网页读取手机联系人,调用手机相

Android通知Notification

一个小demo.点击 发送通知 按钮,则发送通知到设备的通知栏.点击 清除通知 则清除通知栏上的消息通知. package zhangphil.notification; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.app.Activity; import android.app.Notification; import android.app.N

Android数据加密概述及多种加密方式 聊天记录及账户加密 提供高质量的数据保护

Android数据加密概述及多种加密方式 聊天记录及账户加密 提供高质量的数据保护 数据加密又称密码学,它是一门历史悠久的技术,指通过加密算法和加密密钥将明文转变为密文,而解密则是通过解密算法和解密密钥将密文恢复为明文.数据加密目前仍是计算机系统对信息进行保护的一种最可靠的办法.它利用密码技术对信息进行加密,实现信息隐蔽,从而起到保护信息的安全的作用. 一.概述 数据加密是指通过加密算法和加密密钥将明文转变为密文,而解密则是通过解密算法和解密密钥将密文恢复为明文.它产生的历史相当久远,它是起源于

c# winform 中的 工具栏自动隐藏 splitter用法 带源码

代码下载地址 http://download.csdn.net/detail/simadi/7649313 c# winform 中的 工具栏自动隐藏 splitter用法 带源码,布布扣,bubuko.com