(转)android学习---Notification

原文:http://www.cnblogs.com/plokmju/p/android_Notification.html

 

Notificationhtml

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

  注意:由于一些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()方法发送通知。app

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

  虽然通知中提供了各类属性的设置,可是一个通知对象,有几个属性是必需要设置的,其余的属性均是可选的,必须设置的属性以下:ide

  • 小图标,使用setSamllIcon()方法设置。
  • 标题,使用setContentTitle()方法设置。
  • 文本内容,使用setContentText()方法设置。 

  

更新与移除通知函数

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

  对于一个通知,当展现在状态栏以后,可是使用事后,如何取消呢?Android为咱们提供两种方式移除通知,一种是Notification本身维护,使用setAutoCancel()方法设置是否维护,传递一个boolean类型的数据。另一种方式使用NotificationManager通知管理器对象来维护,它经过notify()发送通知的时候,指定的通知标识Id来操做通知,可使用cancel(int)来移除一个指定的通知,也可使用cancelAll()移除全部的通知。测试

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

1         NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2         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高,宽度为屏幕标准。标准视图的通知主体内容有一下几个:

  1. 通知标题。
  2. 大图标。
  3. 通知内容。
  4. 通知消息。
  5. 小图标。
  6. 通知的时间,通常为系统时间,也可使用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("twain@android.com");
                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的使用,模仿上面图片的显示。

   实现代码:

    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("mtwain@android.com"))
                        .build();

                NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(0, noti);
            }
        });

  展现效果:

 

进度条样式的通知

  对于一个标准通知,有时候显示的消息并不必定是静态的,还能够设定一个进度条用于显示事务完成的进度。

  Notification.Builder类中提供一个setProgress(int max,int progress,boolean indeterminate)方法用于设置进度条,max用于设定进度的最大数,progress用于设定当前的进度,indeterminate用因而否是一个肯定进度只的进度条。经过indeterminate的设置,能够实现两种不一样样式的进度条,一种是有进度的(false),一种是循环流动的(false)。下面分别用两个示例演示:

  有进度的进度条,实现代码: 

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

  显示效果:

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

    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代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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" />

</RelativeLayout>

  实现代码:

    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中增长两个受权,分别授予访问振动器与闪光灯的权限:

<!-- 闪光灯权限 -->
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<!-- 振动器权限 -->
<uses-permission android:name="android.permission.VIBRATE"/>

 

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

相关文章
相关标签/搜索