woff 發表於 2014-11-29 00:52:02

Android中通知的使用-----Notification詳解

      Notification ——通知,是一種讓你的應用程序在不使用Activity的情況下警示用戶。它是看不見的程序組件(Broadcast Receiver,Service和不活躍的Activity)警示用戶有需要注意的事件發生的最好途徑。      Notification是由NotificationManager(系統服務)統一管理的。
         一般來說, 一個Notification應該傳送的消息包括:               1 、一個狀態條圖標                     2、在拉伸的狀態欄窗口中顯示額外的信息和啟動一個Application的Intent                3、閃燈或LED               4、電話震動          在狀態欄(Status Bar)中,通知主要有兩類(使用FLAG_標記,後面講解到):                1、正在運行的事件               2、通知事件
         Notification圖解如下:                                                                       通知瑞凱紹:       常量:             //表示發送一個Notification的所攜帶的效果             DEFAULT_ALL 使用默認字段             DEFAULT_LIGHTS 默認閃光             DEFAULT_SOUND 默認聲音(uri,指向路徑)             DEFAULT_VIRATE默認震動,後來得知需要添加震動權限VIBRATE: android.permission.VIBRATE
            PS:以上的效果常量可以累加,​​即通過mNotifaction.defaults |=DEFAULT_SOUND (有些效果只能在真機上才有,比如震動)            //設置Flag位            FLAG_AUTO_CANCEL         該通知能被狀態欄的清除按鈕給清除掉            FLAG_NO_CLEAR                  該通知不能被狀態欄的清除按鈕給清除掉            FLAG_ONGOING_EVENT       通知放置在正在運行           常用字段            contentView通知在狀態欄的顯示View(自定義,具體請看下文) ,常與contentIntent配合使用,點擊該通知後,即觸發contentIntent            contentIntent   設置PendingIntent對象,點擊該通知時發送該Intent flags 設置flag位,例如FLAG_NO_CLEAR等defaults 添加效果            tickerText                     顯示在狀態欄中的文字            when                               發送此通知的時間戳            icon                                 設置圖標             常用方法介紹:            無效setLatestEventInfo(上下文語境,CharSequence的contentTitle,CharSequence的contentText,PendingIntent contentIntent)   
      功能: 顯示在拉伸狀態欄中的Notification屬性,點擊後將發送PendingIntent對象。      參數: context 上下文環境                  contentTitle 狀態欄中的大標題                  contentText 狀態欄中的小標題                  contentIntent 點擊後將發送PendingIntent對象       另外的就是Notification的幾步不同構造方法了,其構造方法的參數含義如上,請參考SDK 。       注意,關於通知(Notification)的顯示類型有兩種:       第一種:使用默認的形式(效果圖如上顯示)。具體使用是為Notification對象設置setLatestEventInfo()方法(該方法內部創建了默認的RemoteViews對象,因此為默認顯示),否則程序會報異常;       第二種:使用自定義的View(RemoteViews對象)顯示 (功能更加自由,強大),具體方法為設置Notification對象的contentView屬性和contentIntent屬性,此時不需要設置setLatestEventInfo()方法。具體使用方法如下:Notification noti = new Notification(icon, title, when + 10000);
noti.flags = Notification.FLAG_INSISTENT;
// 1、創建一個自定義的消息佈局
notification.xml
// 2、在程序代碼中使用RemoteViews的方法來定義image和text。
然後把RemoteViews對像傳到contentView字段
RemoteViews remoteView = new RemoteViews(this.getPackageName(),R.layout.notification);                remoteView.setImageViewResource(R.id.image, R.drawable.icon);                本文采用的RemoteViews資源文件如下:/layout/notification.xml<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="horizontal" android:layout_width="fill_parent"
      android:layout_height="fill_parent">
      <ImageView android:id="@+id/image" android:layout_width="wrap_content"
                android:layout_height="fill_parent" />
      <TextView android:id="@+id/text" android:layout_width="wrap_content"
            android:layout_toRightOf="@+id/image"
                android:layout_height="wrap_content" android:textColor="#000" />
      <ProgressBar android:id="@+id/progress_horizontal"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_below="@+id/text"
                android:layout_toRightOf="@+id/image"
                android:layout_width="fill_parent" android:layout_height="wrap_content"
                android:max="100" android:progress="50" android:secondaryProgress="75" />
</RelativeLayout>
效果圖如下:                                        前面我們說過,NotificationManager是所有Notification的大管家,它的主要職責是加入/移除Notification。NotificationManager類通過獲取系統服務來獲取該對象:NotificationManager mNotificationManager =(NotificationManager)getSystemServic(Context.NOTIFICATION_SERVICE); 常用方法:      public void cancelAll() 移除所有通知(只是針對當前Context下的Notification)      public void cancel (int id)移除標記為id的通知(只是針對當前Context下的所有Notification)      公共無效通知(字符串標記,INT ID,通知通告)將通知加入狀態欄,標籤為標籤,標記為ID      公共無效通知(INT ID,通知通告)將通知加入狀態欄,,標記為ID Demo如下:      說明:示例Demo演示了創建兩種不同類型的Notification ,實現起來也是很簡單的。其實說到兩種不同類型的使用方式,其實內部原理是差不多的。
      PS : 自定義Notification復用了文章之前的佈局文件,請知曉。package com.feixun.qin;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.RemoteViews.RemoteView;

public class MainActivity extends Activity {
      private Button sendNotiBt;
      private int count = 0;
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                sendNotiBt = (Button) findViewById(R.id.sendNotiBt);
                sendNotiBt.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                              // TODO Auto-generated method stub
                              showDefaultNotification();
                        }
                });
      }
      //自定義顯示的通知,創建RemoteView對象
      private void showCustomizeNotification() {
                CharSequence title = "i am new";
                int icon = R.drawable.icon;
                long when = System.currentTimeMillis();
                Notification noti = new Notification(icon, title, when + 10000);
                noti.flags = Notification.FLAG_INSISTENT;
                // 1、創建一個自定義的消息佈局view.xml
                // 2、在程序代碼中使用RemoteViews的方法來定義image和text。然後把RemoteViews對像傳到contentView字段
                RemoteViews remoteView = new RemoteViews(this.getPackageName(),R.layout.notification);
                remoteView.setImageViewResource(R.id.image, R.drawable.icon);
                remoteView.setTextViewText(R.id.text , "通知類型為:自定義View");
                noti.contentView = remoteView;
                // 3、為Notification的contentIntent字段定義一個Intent(注意,使用自定義View不需要setLatestEventInfo()方法)
                //這兒點擊後簡單啟動Settings模塊
                PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0,new Intent("android.settings.SETTINGS"), 0);
                noti.contentIntent = contentIntent;
                NotificationManager mnotiManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                mnotiManager.notify(0, noti);
      }
      // 默認顯示的的Notification
      private void showDefaultNotification() {
            // 定義Notication的各種屬性
            CharSequence title = "i am new";
            int icon = R.drawable.icon;
            long when = System.currentTimeMillis();
            Notification noti = new Notification(icon, title, when + 10000);
            noti.flags = Notification.FLAG_INSISTENT;
            // 創建一個通知
            Notification mNotification = new Notification();
            // 設置屬性值
            mNotification.icon = R.drawable.icon;
            mNotification.tickerText = "NotificationTest";
            mNotification.when = System.currentTimeMillis(); // 立即發生此通知
            // 帶參數的構造函數,屬性值如上
            // Notification mNotification = = new Notification(R.drawable.icon,"NotificationTest", System.currentTimeMillis()));
            // 添加聲音效果
            mNotification.defaults |= Notification.DEFAULT_SOUND;
            // 添加震動,後來得知需要添加震動權限: Virbate Permission
            //mNotification.defaults |= Notification.DEFAULT_VIBRATE ;
            //添加狀態標誌
            //FLAG_AUTO_CANCEL 該通知能被狀態欄的清除按鈕給清除掉
            //FLAG_NO_CLEAR 該通知能被狀態欄的清除按鈕給清除掉
            //FLAG_ONGOING_EVENT 通知放置在正在運行
            //FLAG_INSISTENT 通知的音樂效果一直播放
            mNotification.flags = Notification.FLAG_INSISTENT ;
            //將該通知顯示為默認View
            PendingIntent contentIntent = PendingIntent.getActivity (MainActivity.this, 0,new Intent("android.settings.SETTINGS"), 0);
            mNotification.setLatestEventInfo(MainActivity.this, "通知類型:默認View", "一般般喲。。。。",contentIntent);
         
            // 設置setLatestEventInfo方法,如果不設置會App報錯異常
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            
            //註冊此通知
            // 如果該NOTIFICATION_ID的通知已存在,會顯示最新通知的相關信息,比如tickerText 等
            mNotificationManager.notify(2, mNotification);
      }
    private void removeNotification()
      {
            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            // 取消的只是當前Context的Notification
            mNotificationManager.cancel(2);
      }      
}
轉帖:http://blog.csdn.net/qinjuning/article/details/6915482

頁: [1]
查看完整版本: Android中通知的使用-----Notification詳解