TShopping

 找回密碼
 註冊
搜索
查看: 1455|回復: 0

[教學] Android中通知的使用-----Notification詳解

[複製鏈接]
發表於 2014-11-29 00:52:02 | 顯示全部樓層 |閱讀模式
 
Push to Facebook

      Notification ——通知,是一種讓你的應用程序在不使用Activity的情況下警示用戶。它是看不見的程序組件(Broadcast Receiver,Service和不活躍的Activity)警示用戶有需要注意的事件發生的最好途徑。

      Notification是由NotificationManager(系統服務)統一管理的。


         一般來說, 一個Notification應該傳送的消息包括:

                 1 、一個狀態條圖標        

                 2、在拉伸的狀態欄窗口中顯示額外的信息和啟動一個Application的Intent

                 3、閃燈或LED

                 4、電話震動

         在狀態欄(Status Bar)中,通知主要有兩類(使用FLAG_標記,後面講解到):

                 1、正在運行的事件

                 2、通知事件


         Notification圖解如下:

                                                            1.gif

            

通知瑞凱紹:

         常量

             //表示發送一個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()方法。具體使用方法如下:

  1. Notification noti = new Notification(icon, title, when + 10000);
  2. noti.flags = Notification.FLAG_INSISTENT;
  3. // 1、創建一個自定義的消息佈局
  4. notification.xml
  5. // 2、在程序代碼中使用RemoteViews的方法來定義image和text。
  6. 然後把RemoteViews對像傳到contentView字段
  7. RemoteViews remoteView = new RemoteViews(this.getPackageName(),R.layout.notification);                remoteView.setImageViewResource(R.id.image, R.drawable.icon);               
複製代碼

本文采用的RemoteViews資源文件如下:/layout/notification.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.         android:orientation="horizontal" android:layout_width="fill_parent"
  4.         android:layout_height="fill_parent">
  5.         <ImageView android:id="@+id/image" android:layout_width="wrap_content"
  6.                 android:layout_height="fill_parent" />
  7.         <TextView android:id="@+id/text" android:layout_width="wrap_content"
  8.             android:layout_toRightOf="@+id/image"
  9.                 android:layout_height="wrap_content" android:textColor="#000" />
  10.         <ProgressBar android:id="@+id/progress_horizontal"
  11.                 style="?android:attr/progressBarStyleHorizontal"
  12.                 android:layout_below="@+id/text"
  13.                 android:layout_toRightOf="@+id/image"
  14.                 android:layout_width="fill_parent" android:layout_height="wrap_content"
  15.                 android:max="100" android:progress="50" android:secondaryProgress="75" />
  16. </RelativeLayout>
複製代碼

效果圖如下:

                                          2.gif

  前面我們說過,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復用了文章之前的佈局文件,請知曉。

  1. package com.feixun.qin;

  2. import android.app.Activity;
  3. import android.app.Notification;
  4. import android.app.NotificationManager;
  5. import android.app.PendingIntent;
  6. import android.content.BroadcastReceiver;
  7. import android.content.Context;
  8. import android.content.Intent;
  9. import android.content.IntentFilter;
  10. import android.net.Uri;
  11. import android.os.Bundle;
  12. import android.provider.MediaStore.Audio;
  13. import android.util.Log;
  14. import android.view.View;
  15. import android.widget.Button;
  16. import android.widget.RemoteViews;
  17. import android.widget.RemoteViews.RemoteView;

  18. public class MainActivity extends Activity {
  19.         private Button sendNotiBt;
  20.         private int count = 0;
  21.         /** Called when the activity is first created. */
  22.         @Override
  23.         public void onCreate(Bundle savedInstanceState) {
  24.                 super.onCreate(savedInstanceState);
  25.                 setContentView(R.layout.main);
  26.                 sendNotiBt = (Button) findViewById(R.id.sendNotiBt);
  27.                 sendNotiBt.setOnClickListener(new View.OnClickListener() {
  28.                         @Override
  29.                         public void onClick(View v) {
  30.                                 // TODO Auto-generated method stub
  31.                                 showDefaultNotification();
  32.                         }
  33.                 });
  34.         }
  35.         //自定義顯示的通知,創建RemoteView對象
  36.         private void showCustomizeNotification() {
  37.                 CharSequence title = "i am new";
  38.                 int icon = R.drawable.icon;
  39.                 long when = System.currentTimeMillis();
  40.                 Notification noti = new Notification(icon, title, when + 10000);
  41.                 noti.flags = Notification.FLAG_INSISTENT;
  42.                 // 1、創建一個自定義的消息佈局view.xml
  43.                 // 2、在程序代碼中使用RemoteViews的方法來定義image和text。然後把RemoteViews對像傳到contentView字段
  44.                 RemoteViews remoteView = new RemoteViews(this.getPackageName(),R.layout.notification);
  45.                 remoteView.setImageViewResource(R.id.image, R.drawable.icon);
  46.                 remoteView.setTextViewText(R.id.text , "通知類型為:自定義View");
  47.                 noti.contentView = remoteView;
  48.                 // 3、為Notification的contentIntent字段定義一個Intent(注意,使用自定義View不需要setLatestEventInfo()方法)
  49.                 //這兒點擊後簡單啟動Settings模塊
  50.                 PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0,new Intent("android.settings.SETTINGS"), 0);
  51.                 noti.contentIntent = contentIntent;
  52.                 NotificationManager mnotiManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
  53.                 mnotiManager.notify(0, noti);
  54.         }
  55.         // 默認顯示的的Notification
  56.         private void showDefaultNotification() {
  57.             // 定義Notication的各種屬性
  58.             CharSequence title = "i am new";
  59.             int icon = R.drawable.icon;
  60.             long when = System.currentTimeMillis();
  61.             Notification noti = new Notification(icon, title, when + 10000);
  62.             noti.flags = Notification.FLAG_INSISTENT;
  63.             // 創建一個通知
  64.             Notification mNotification = new Notification();
  65.             // 設置屬性值
  66.             mNotification.icon = R.drawable.icon;
  67.             mNotification.tickerText = "NotificationTest";
  68.             mNotification.when = System.currentTimeMillis(); // 立即發生此通知
  69.             // 帶參數的構造函數,屬性值如上
  70.             // Notification mNotification = = new Notification(R.drawable.icon,"NotificationTest", System.currentTimeMillis()));
  71.             // 添加聲音效果
  72.             mNotification.defaults |= Notification.DEFAULT_SOUND;
  73.             // 添加震動,後來得知需要添加震動權限: Virbate Permission
  74.             //mNotification.defaults |= Notification.DEFAULT_VIBRATE ;
  75.             //添加狀態標誌
  76.             //FLAG_AUTO_CANCEL 該通知能被狀態欄的清除按鈕給清除掉
  77.             //FLAG_NO_CLEAR 該通知能被狀態欄的清除按鈕給清除掉
  78.             //FLAG_ONGOING_EVENT 通知放置在正在運行
  79.             //FLAG_INSISTENT 通知的音樂效果一直播放
  80.             mNotification.flags = Notification.FLAG_INSISTENT ;
  81.             //將該通知顯示為默認View
  82.             PendingIntent contentIntent = PendingIntent.getActivity (MainActivity.this, 0,new Intent("android.settings.SETTINGS"), 0);
  83.             mNotification.setLatestEventInfo(MainActivity.this, "通知類型:默認View", "一般般喲。。。。",contentIntent);
  84.          
  85.             // 設置setLatestEventInfo方法,如果不設置會App報錯異常
  86.             NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  87.             
  88.             //註冊此通知
  89.             // 如果該NOTIFICATION_ID的通知已存在,會顯示最新通知的相關信息,比如tickerText 等
  90.             mNotificationManager.notify(2, mNotification);
  91.         }
  92.     private void removeNotification()
  93.         {
  94.             NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  95.             // 取消的只是當前Context的Notification
  96.             mNotificationManager.cancel(2);
  97.         }        
  98. }
複製代碼
轉帖:http://blog.csdn.net/qinjuning/article/details/6915482


 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-3-29 18:23 , Processed in 0.062990 second(s), 26 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表