notification出现在通知栏中的提示,特别是在4.0以后改进了不少,这里讲得都是基于4.0及4.1以后的。

分类:

1.普通Notification

2.大布局Notification

            图1

大布局notification在android 4.0以后才增加,与小布局只在"7"部分有区别,其他部分都一致。

大布局notification只有在所有notifacation的最上面时才会显示大布局,其他情况下显示小布局,当然你也可以用手指将其扩展为大布局(前提是,它是大布局),效果图:

                   图2

大布局notification有三种类型:如图1为NotificationCompat.InboxStyle类型;图2左为NotificationCompat.BigTextStyle;图2右部为:NotificationCompat.BigPictureStyle。

3.自定义布局Notification

如下图所示的一个音乐播放器控制notification

如何创建notification

     1>实例化一个NotificationCompat.Builder对象;如builder

     2>调用builder的相关方法对notification进行上面提到的各种设置

    3>调用builder.build()方法此方法返回一个notification对象。

     4>实例化一个NotificationManager对象;如:manager

     5>调用manager的notify方法。

  注:

  一个notification不必对上面所有的选项都进行设置,但有3项是必须的:

   小图标, set by setSmallIcon()

     内容标题, set by setContentTitle()

     内容, set by setContentText()

package com.example.notification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.EditText;
/**
 * 需求:将编辑框的内容显示在Notification中
 * @author joanna.yan
 *
 */
public class MainActivity extends Activity {
    EditText etText;
    int id=1;
    private Bitmap icon;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        etText=(EditText) findViewById(R.id.etText);

        icon = BitmapFactory.decodeResource(getResources(),
                 R.drawable.ic_launcher);
    }

    public void send(View view){
        String message=etText.getText().toString();

        Intent intent=new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("http://www.baidu.com"));

        PendingIntent pendingIntent=PendingIntent.getActivity(this, 1000, intent, PendingIntent.FLAG_ONE_SHOT);//FLAG_ONE_SHOT只能用一次
        //定义一个通知对象
        NotificationCompat.Builder builder=new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.msg_icon)
            .setLargeIcon(icon)
            .setContentTitle("您有新消息")
            .setContentText(message)
            .setAutoCancel(true)  //设置点击后自动消失
            .setDefaults(Notification.DEFAULT_SOUND)   //默认铃声
            .setContentIntent(pendingIntent);  //设置点击消息后的反应

        //需要一个管理通知框的对象
        NotificationManager manager=(NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);
        //manager.notify(1, builder.build());//如果第一个参数的值指定死了,比如一个具体的数字,那么通知框中只会显示1条,当发生多条时,后面的会覆盖前面的
        manager.notify(id++, builder.build());//发送了几次就会显示几条,不会被覆盖

    }

}

示例代码

程序截图:

0)初始化部分代码

 public class MainActivity extends Activity implements OnClickListener {

     private static final int NOTIFICATION_ID_1 = 0;
     private static final int NOTIFICATION_ID_2 = 1;
     private static final int NOTIFICATION_ID_3 = 2;
     private static final int NOTIFICATION_ID_4 = 3;
     private static final int NOTIFICATION_ID_5 = 4;
     private static final int NOTIFICATION_ID_6 = 5;
     private static final int NOTIFICATION_ID_7 = 6;
     private static final int NOTIFICATION_ID_8 = 7;

     private static int messageNum = 0;
     private Context context = this;
     private NotificationManager manager;
     private Bitmap icon;
     private static final int[] btns = new int[] { R.id.btn1, R.id.btn2,
             R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8,
             R.id.btn9 };

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         init();
     }

     private void init() {
         // 获取通知服务
         manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
         // 注册监听器
         for (int btn : btns) {
             findViewById(btn).setOnClickListener(this);
         }

         icon = BitmapFactory.decodeResource(getResources(),
                 R.drawable.ic_launcher);
     }

     @Override
     public void onClick(View v) {
         switch (v.getId()) {
         case R.id.btn1:
             showNormal();
             break;
         case R.id.btn2:
             showBigView_Text();
             break;
         case R.id.btn3:
             showBigView_Pic();
             break;
         case R.id.btn4:
             showBigView_Inbox();
             break;
         case R.id.btn5:
             showCustomView();
             break;
         case R.id.btn6:
             backApp();
             break;
         case R.id.btn7:
             backScreen();
             break;
         case R.id.btn8:
             showProgressBar();
             break;
         case R.id.btn9:
             dismiss();
             break;
         default:
             Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
             break;
         }
     }

     private void dismiss() {
         manager.cancelAll();
     }

1)普通Notification

 private void showNormal() {

         Notification notification = new NotificationCompat.Builder(context)
                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("showNormal").setContentInfo("contentInfo")
                 .setContentTitle("ContentTitle").setContentText("ContentText")
                 .setNumber(++messageNum)
                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                 .build();
         manager.notify(NOTIFICATION_ID_1, notification);
     }

2)大布局Text类型notification

 private void showBigView_Text() {
         NotificationCompat.BigTextStyle textStyle = new BigTextStyle();
         textStyle
                 .setBigContentTitle("BigContentTitle")
                 .setSummaryText("SummaryText")
                 .bigText(
                         "I am Big Texttttttttttttttttttttttttttttttttttttttttttt!!!!!!!!!!!!!!!!!!!......");
         Notification notification = new NotificationCompat.Builder(context)
                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("showBigView_Text").setContentInfo("contentInfo")
                 .setContentTitle("ContentTitle").setContentText("ContentText")
                 .setStyle(textStyle)
                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                 .build();
         manager.notify(NOTIFICATION_ID_2, notification);
     }

3)大布局Picture类型notification

private void showBigView_Pic() {
         NotificationCompat.BigPictureStyle pictureStyle = new BigPictureStyle();
         pictureStyle.setBigContentTitle("BigContentTitle")
                 .setSummaryText("SummaryText").bigPicture(icon);
         Notification notification = new NotificationCompat.Builder(context)
                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("showBigView_Pic").setContentInfo("contentInfo")
                 .setContentTitle("ContentTitle").setContentText("ContentText")
                 .setStyle(pictureStyle)
                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                 .build();
         manager.notify(NOTIFICATION_ID_3, notification);
     }

4)大布局Inbox类型notification

 private void showBigView_Inbox() {
         NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
         inboxStyle.setBigContentTitle("BigContentTitle").setSummaryText(
                 "SummaryText");
         for (int i = 0; i < 5; i++)
             inboxStyle.addLine("news:" + i);
         Notification notification = new NotificationCompat.Builder(context)
                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("showBigView_Inbox").setContentInfo("contentInfo")
                 .setContentTitle("ContentTitle").setContentText("ContentText")
                 .setStyle(inboxStyle)
                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
                 .build();
         manager.notify(NOTIFICATION_ID_4, notification);
     }

4)自定义notification

并对中间的播放按钮做了一个简单的点击处理事件(点击播放后,请关闭幕帘否则可能会看不到toast提示)

效果图:

代码:

private void showCustomView() {
         RemoteViews remoteViews = new RemoteViews(getPackageName(),
                 R.layout.custom_notification);
         Intent intent = new Intent(this, TestMusicControl.class);
         PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                 intent, 0);
         remoteViews.setOnClickPendingIntent(R.id.paly_pause_music,
                 pendingIntent);
         NotificationCompat.Builder builder = new Builder(context);
         builder.setContent(remoteViews).setSmallIcon(R.drawable.music_icon)
                 .setLargeIcon(icon).setOngoing(true)
                 .setTicker("music is playing");
         manager.notify(NOTIFICATION_ID_8, builder.build());
     }

布局文件:

 <?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="match_parent"
     android:gravity="center_vertical"
     android:orientation="horizontal" >

     <ImageView
         android:id="@+id/songer_pic"
         android:layout_width="64dp"
         android:layout_height="64dp"
         android:src="@drawable/yan" />

     <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:gravity="center_vertical"
         android:orientation="horizontal" >

         <ImageView
             android:id="@+id/last_music"
             android:layout_width="0dp"
             android:layout_height="48dp"
             android:layout_weight="1"
             android:src="@drawable/music_previous" />

         <ImageView
             android:id="@+id/paly_pause_music"
             android:layout_width="0dp"
             android:layout_height="48dp"
             android:layout_weight="1"
             android:src="@drawable/music_play" />

         <ImageView
             android:id="@+id/next_music"
             android:layout_width="0dp"
             android:layout_height="48dp"
             android:layout_weight="1"
             android:src="@drawable/music_next" />
     </LinearLayout>

 </LinearLayout>

5)带进度条的notification

 private void showProgressBar() {

         final NotificationCompat.Builder builder = new NotificationCompat.Builder(
                 context);
         builder.setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("showProgressBar").setContentInfo("contentInfo")
                 .setOngoing(true).setContentTitle("ContentTitle")
                 .setContentText("ContentText");
         new Thread(new Runnable() {

             @Override
             public void run() {

                 int progress = 0;

                 for (progress = 0; progress < 100; progress += 5) {
                     //将setProgress的第三个参数设为true即可显示为无明确进度的进度条样式
                     builder.setProgress(100, progress, false);
                     manager.notify(NOTIFICATION_ID_7, builder.build());
                     try {
                         // Sleep for 5 seconds
                         Thread.sleep(2 * 1000);
                     } catch (InterruptedException e) {
                         System.out.println("sleep failure");
                     }
                 }
                 builder.setContentTitle("Download complete")
                         .setProgress(0, 0, false).setOngoing(false);
                 manager.notify(NOTIFICATION_ID_7, builder.build());

             }
         }).start();
     }

-------------------------------------------------------------------------------------------------------------------------------------------

点击事件的处理

1)返回应用住界面

有时候我们可能需要实现这样的功能:当新notification出现时,我们希望点击它后可直接进入应用相应的界面中去完整查看或处理此消息的功能。然后,当我们点击back按钮时返回到应用主界面而不是桌面。比如:当我们有新的短信来时,我们在任务栏中点击它后进入读信息页面,当我们读完短信后,按“返回”键回到短信的主界面,而不是手机桌面。要实现这样的功能要我们做相应的处理:

 private void backApp() {

         TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
         // Adds the back stack
         stackBuilder.addParentStack(OtherActivity.class);
         // Adds the Intent to the top of the stack
         Intent resultIntent = new Intent(this, OtherActivity.class);
         stackBuilder.addNextIntent(resultIntent);
         // Gets a PendingIntent containing the entire back stack
         PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                 PendingIntent.FLAG_UPDATE_CURRENT);

         Notification notification = new NotificationCompat.Builder(context)
                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("backApp").setContentInfo("contentInfo")
                 .setContentTitle("ContentTitle").setContentText("ContentText")
                 .setContentIntent(resultPendingIntent).setAutoCancel(true)
                 .setDefaults(Notification.DEFAULT_ALL).build();
         manager.notify(NOTIFICATION_ID_5, notification);
         this.finish();
     }

并需要我们在配置文件中对我们用来显示详细信息的OtherActivity进行相应的配置如下:

<activity
             android:name="com.example.notification.OtherActivity"
             android:label="@string/title_activity_other"
             android:parentActivityName=".MainActivity" >
             <meta-data
                 android:name="android.support.PARENT_ACTIVITY"
                 android:value=".MainActivity" />
         </activity>

2)直接返回桌面

有些时候我们可能需要实现这样的功能:当我们点击notification时弹出一个稍大点的窗口来显示整个消息,这窗口的作用就是用来显示整个消息内容的,和此应用内的其它Activity都没有关系,然后当我们点击"back"后直接返回到手机桌面。要实现这样的功能我们只需要调用builder的.setContentIntent方法,然后对所要跳转到的activity在配置文件中进行一些配置:

private void backScreen() {
         Intent notifyIntent = new Intent(this, SpecialActivity.class);
         // Sets the Activity to start in a new, empty task
         notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                 | Intent.FLAG_ACTIVITY_CLEAR_TASK);
         // Creates the PendingIntent
         PendingIntent notify_Intent = PendingIntent.getActivity(this, 0,
                 notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

         Notification notification = new NotificationCompat.Builder(context)
                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("backScreen").setContentInfo("contentInfo")
                 .setContentTitle("ContentTitle").setContentText("ContentText")
                 .setContentIntent(notify_Intent).setAutoCancel(true)
                 .setDefaults(Notification.DEFAULT_ALL).build();
         manager.notify(NOTIFICATION_ID_6, notification);
         this.finish();
     }

配置文件:

 <activity
             android:name="com.example.notification.SpecialActivity"
             android:excludeFromRecents="true"
             android:label="@string/title_activity_special"
             android:launchMode="singleTask"
             android:taskAffinity="" >

源代码:

链接:http://pan.baidu.com/s/1sj9KVYP 密码:uwsq11

Android notification的使用的更多相关文章

  1. Android Notification 详解(一)——基本操作

    Android Notification 详解(一)--基本操作 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Notification 文中如有纰 ...

  2. Android Notification 详解——基本操作

    Android Notification 详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 前几天项目中有用到 Android 通知相关的内容,索性把 Android Notificatio ...

  3. 3、android notification 详细用法

    在 android 系统中,在应用程序可能会遇到几种情况需要通知用户,有的需要用户回应,有的则不需要,例如: * 当保存文件等事件完成,应该会出现一个小的消息,以确认保存成功. * 如果应用程序在后台 ...

  4. android notification 传值关键

    android notification 传值关键在 onNewIntent方法里获取 @Override protected void onCreate(Bundle savedInstanceSt ...

  5. Android NOtification 使用(震动 闪屏 铃声)

    一. Notification 简介 在 android 系统中,在应用程序可能会遇到几种情况需要通知用户,有的需要用户回应,有的则不需要,例如: * 当保存文件等事件完成,应该会出现一个小的消息,以 ...

  6. Android Notification通知详细解释

    Android Notification通知具体解释  Notification: (一).简单介绍:         显示在手机状态栏的通知. Notification所代表的是一种具有全局效果的通 ...

  7. Android Notification实现推送消息过程中接受到消息端有声音及震动及亮屏提示

    在Android Notification状态栏通知一文中,简单实现了消息的推送效果,这里就接着上文说一下,当用户接受到消息时的提示效果 // 5-增加震动及声音及亮屏 notification.de ...

  8. Android Notification通知简介

    Android Notification通知简介 根据activity的生命周期,在activity不显示时,会执行onStop函数(比如按下home键),所以你在onStop函数(按退出键除外)里面 ...

  9. Android Notification状态栏通知

    没有添加额外的震动及声音效果,这里直接实现了通知的功能,看效果吧: MainActivity.java package com.example.notification; import android ...

  10. Android Notification 消息通知 相关资料.md

    目录 Android Notification 消息通知 相关资料 Android 5.0 Lollipop (API 21)无法正常显示通知图标,只能看到一个白色方块或灰色方块的问题 解决方案 参考 ...

随机推荐

  1. java-类加载器

    类加载器 用来加载Java类到Java虚拟机中.一般来说,Java虚拟机使用Java类的方式如下:Java 源程序(.java 文件)在经过Java编译器编译之后就被转换成字节码(.class 文件) ...

  2. WCF服务配置问题

      上一篇中,我们主要是使用了代码来实现服务的自我寄宿.代码的实现稍微复杂些,不过还有些使用配置文件和配置工具的方法.下面来一一介绍下.     1.配置文件.首先在Host下添加个app.confi ...

  3. onBlur事件与onfocus事件(js)

      onFocus事件就是当光标落在文本框中时发生的事件. onBlur事件是光标失去焦点时发生的事件. 可以编如下例子 1.html <HTML><HEAD><TITL ...

  4. php中explode与split的区别介绍

    php中explode与split的区别介绍 作者: 字体:[增加 减小] 类型:转载 今天在使用split时遇到一些问题.还是对函数理解不深刻,特写出来做个记 首先来看下两个方法的定义: 函数原型: ...

  5. 《Python标准库》 目录

    目录 译者序序前言第1章 文本1.1 string—文本常量和模板1.1.1 函数1.1.2 模板1.1.3 高级模板1.2 textwrap—格式化文本段落1.2.1 示例数据1.2.2 填充段落1 ...

  6. iOS开发-UINavigationBar透明设置

    导航条最近需要设置成透明的形式,最开始想通过颜色clearColor设置,设置透明度,结果发现UINavigationItem无法显示显示,后来通过setBackgroundImage设置成功,不过会 ...

  7. Centos6.6下安装MariaDB步骤,利用yum进行安装 第二篇

    一.安装过程参考的相关文章: Centos 使用YUM安装MariaDB CentOS安装并设置MariaDB CentOS用yum安装.配置MariaDB MariaDB远程连接配置 ERROR 1 ...

  8. [.NET领域驱动设计实战系列]专题四:前期准备之工作单元模式(Unit Of Work)

    一.前言 在前一专题中介绍了规约模式的实现,然后在仓储实现中,经常会涉及工作单元模式的实现.然而,在我的网上书店案例中也将引入工作单元模式,所以本专题将详细介绍下该模式,为后面案例的实现做一个铺垫. ...

  9. 设计模式之美:Type Object(类型对象)

    索引 意图 结构 参与者 适用性 效果 相关模式 实现 实现方式(一):Type Object 的经典介绍. 实现方式(二):Type Object 在游戏设计中的使用. 意图 允许在运行时动态灵活的 ...

  10. XP之后Windows的一些变化

    看到很多Windows开发人员,尤其是C++程序员思维还是停留在XP操作系统,当然根据工作是否需要新知识 ,这本身没有错.但是实际上Vista之后的Win7, 再之后的Win8 ,Windows已经发 ...