android notification 的总结分析

notification是一种出现在任务栏的提示,特别是在4.0以后notification改进了不少,本文内容都是基于4.0及4.1以后总结来的

分类

notification有以下几种:

  1>普通notification

  

    1.内容标题

    2.大图标

    3.内容

    4.内容附加信息

    5.小图标

    6.时间

  2>大布局Notification

    图1

  大布局notification是在android4.1以后才增加的,大布局notification与小布局notification只在‘7‘部分有区别,其它部分都一致。大布局notification只有在所有notification的最上  面时才会显示大布局,其它情况下显示小布局。你也可以用手指将其扩展为大布局(前提是它是大布局)。如下图:

  图2

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

   3>自定义布局notification

    除了系统提供的notification,我们也可以自定义notification。如下图所示的一个音乐播放器控制notification:

    图3

如何创建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()

示例代码




示例程序截图:



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

复制代码代码如下:

View
Code 
     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类型notificatio

复制代码代码如下:

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

5>自定义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>

带进度条的notification

复制代码代码如下:

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

点击事件处理 

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

1>返回应用主界面

复制代码代码如下:

View
Code 
     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://www.jb51.net/article/36567.htm

参考:http://developer.android.com/guide/topics/ui/notifiers/notifications.html

时间: 2024-08-08 00:14:29

android notification 的总结分析的相关文章

android Notification分析——你可能遇到的各种问题

通知的使用网上有各种总结,csdn上也有很多总结非常到位,在此就不做重复的总结了,需要的同学可以自行搜索或者参考下面给出的链接.开始学习的时候认真的读了一些,现在功能开发完毕,把自己最近遇到的一些问题和心得分享给大家. 一.很难逃避de兼容问题 1.直接new Notification()这种方式已经过时,因此自己也没有去细究这种方式,直接使用的是new NotificationCompat.Builder(context).build()(这个在support v4包中,下面的内容全是以这种方

Android平台PreferenceActivity组件分析

1.PreferenceActivity 介绍 PreferenceActivity 继承ListActivity 它是以一个列表的形式在展现内容,它最主要的特点是添加Preference可以让控件的状态持久化储存,举个例子 比如用户选中checkbox后 退出应用然后在进入应用,这时用户希望看到的是checkbox被选中,所以软件须要记录用户每次操作的过程并且持久储存,在进入应用的时候须要判断这些久储存的数据然后将系统控件的状态呈现在UI中. 尤其是软件开发肯定会有一堆设置选项选项,每次进入A

Android -- Wifi连接流程分析

Android -- Wifi连接流程分析 当我们在Android手机上连接一个AP时,间接调用WifiManager的connect()方法: /** * Connect to a network with the given configuration. The network also * gets added to the supplicant configuration. * * For a new network, this function is used instead of a

Android debuggerd 源码分析

debuggerd 简介 Android系统自带一个实用的程序异常退出的诊断daemon debuggerd.此进程可以侦测到程序崩溃,并将崩溃时的进程状态信息输出到文件和串口中,以供开发人员分析调试使用.Debuggerd的数据被保存在/data/tombstone/目录下,共可保存10个文件,当超过10个时,会覆盖重写最早生产的文件.串口中,则直接用DEBUG的tag,输出logcat信息. Linux kernel有自己的一套signal机制,在应用程序崩溃时,通常系统内核都会发送sign

android Notification 的使用(锁定通知栏)

最近一直在研究 android ,并一边研究一边做应用.其中遇到了把程序通知常驻在 Notification 栏,并且不能被 clear 掉(就像android QQ一样)的问题.经过研究实现了其功能,现把 Notification 的使用总结如下: Notification 的使用需要导入 3 个类 1 2 3 import android.app.PendingIntent; import android.app.NotificationManager; import android.app

Android PhoneGap源码分析——白名单

对于单独的Web app应用来说,加载进来的url一般不能保证它的安全性.那么如何来处理url安全性的问题呢. 让我们来看看PhoneGap是如何做的. PhoneGap采用了白名单的形式,认为在白名单中的url认为是安全的,不在白名单中的url是不安全的.对于安全的url,PhoneGap的Web app会直接打开,对于不安全的url,会通过浏览器打开. 那么怎么增加白名单呢?PhoneGap是需要在配置文件res/xml/config.xml中设置,如下: <cordova> - <

[Android]Fragment源码分析(一) 构造

Fragment是Android3.0之后提供的api,被大家广泛所熟知的主要原因还是因为随即附带的ViewPager控件.虽然我并不喜欢用它,但是它确实是一个相对不错的控件.还是我的一贯作风,我将从源码上向大家展示什么是Fragment.我们先写一个简单的代码对Fragment有个直观的认识:(为了保证我们方便调试,我们可以直接使用V4提供的源码包) FragmentTransaction t = getSupportFragmentManager().beginTransaction();

android:clipChildren属性的分析——是否剪裁子View

MainActivity如下: package cc.testclipchildren; import android.os.Bundle; import android.app.Activity; /** * android:clipChildren属性的分析 * 该属性默认值为android:clipChildren="true" * 单从字面意思理解clipChildren的意思是:裁剪(缩短)孩子 * 我们将其值设置为false后那么当子控件的高度高于父控件时 * 也会完全显示

android:clipToPadding属性的分析——以ListView的&quot;别样&quot;padding为例

MainActivity如下: package cn.com.bravesoft.testlistviewloadmore; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleAdapter; /** * Dem