Android中Notification詳解

下面來談?wù)刵otification讲仰,這個notification一般用在電話,短信漾峡,郵件攻旦,鬧鐘鈴聲,在手機的狀態(tài)欄上就會出現(xiàn)一個小圖標(biāo)生逸,提示用戶處理這個快訊牢屋,這時手從上方滑動狀態(tài)欄就可以展開并處理這個快訊。發(fā)現(xiàn)這個功能特別好用槽袄,所以我就根據(jù)我的理解來談?wù)劺游蕖U詭椭臋n : notification類表示一個持久的通知,將提交給用戶使用NotificationManager遍尺。已添加的Notification.Builder截酷,使其更容易構(gòu)建通知。notification是一種讓你的應(yīng)用程序在沒有開啟情況下或在后臺運行警示用戶乾戏。它是看不見的程序組件(Broadcast Receiver迂苛,Service和不活躍的Activity)警示用戶有需要注意的事件發(fā)生的最好途徑。

先來區(qū)分以下**狀態(tài)欄和狀態(tài)條**的區(qū)別:
1鼓择、狀態(tài)條就是手機屏幕最上方的一個條形狀的區(qū)域三幻;
      在狀態(tài)條有好多信息量:比如usb連接圖標(biāo),手機信號圖標(biāo)呐能,電池電量圖標(biāo)念搬,時間圖標(biāo)等等;
2摆出、狀態(tài)欄就是手從狀態(tài)條滑下來的可以伸縮的view朗徊;
      在狀態(tài)欄中一般有兩類(使用FLAG_標(biāo)記):
      (1)正在進行的程序;
      (2)是通知事件偎漫;

 大概來描述創(chuàng)建一個Notification傳送的信息有:
1荣倾、**一個狀態(tài)條圖標(biāo);**
2骑丸、**在拉伸的狀態(tài)欄窗口中顯示帶有大標(biāo)題舌仍,小標(biāo)題妒貌,圖標(biāo)的信息,并且有處理該點擊事件:比如調(diào)用該程序的入口類铸豁; **

** 3灌曙、閃光,LED节芥,或者震動在刺;**


  快速創(chuàng)建一個Notification的步驟簡單可以分為以下四步:
  **第一步**:通過getSystemService()方法得到NotificationManager對象;
  **第二步**:對Notification的一些屬性進行設(shè)置比如:內(nèi)容头镊,圖標(biāo)蚣驼,標(biāo)題,相應(yīng)notification的動作進行處理等等相艇;
  **第三步**:通過NotificationManager對象的notify()方法來執(zhí)行一個notification的快訊颖杏;
**  第四步**:通過NotificationManager對象的cancel()方法來取消一個notificatioin的快訊;

 下面對Notification類中的一些常量坛芽,字段留储,方法簡單介紹一下:
 常量:
    DEFAULT_ALL                  使用所有默認值,比如聲音咙轩,震動获讳,閃屏等等
    DEFAULT_LIGHTS            使用默認閃光提示
    DEFAULT_SOUNDS         使用默認提示聲音
    DEFAULT_VIBRATE         使用默認手機震動 
  【**說明】:加入手機震動,一定要在manifest.xml中加入權(quán)限:**

** ****<uses-permission android:name="android.permission.VIBRATE" />**
以上的效果常量可以疊加,即通過
mNotifaction.defaults =DEFAULT_SOUND | DEFAULT_VIBRATE ;
或mNotifaction.defaults |=DEFAULT_SOUND (最好在真機上測試活喊,震動效果模擬器上沒有)

    //設(shè)置flag位

** FLAG_AUTO_CANCEL** 該通知能被狀態(tài)欄的清除按鈕給清除掉
** FLAG_NO_CLEAR** 該通知能被狀態(tài)欄的清除按鈕給清除掉
FLAG_ONGOING_EVENT 通知放置在正在運行
** FLAG_INSISTENT ** 是否一直進行丐膝,比如音樂一直播放,知道用戶響應(yīng)

  常用字段:
       **contentIntent**                  設(shè)置PendingIntent對象钾菊,點擊時發(fā)送該Intent
       defaults                             添加默認效果
       flags                                  設(shè)置flag位帅矗,例如FLAG_NO_CLEAR等
       **icon **                                 設(shè)置圖標(biāo)
       sound                                設(shè)置聲音
       **tickerText**                        顯示在狀態(tài)欄中的文字
      ** when                                **發(fā)送此通知的時間戳

Notification.build構(gòu)造Notification方法介紹: ** **
** ** void setLatestEventInfo(Context context , CharSequencecontentTitle,CharSequence contentText,PendingIntent contentIntent)


** **功能: 顯示在拉伸狀態(tài)欄中的Notification屬性,點擊后將發(fā)送PendingIntent對象
參數(shù): context 上下文環(huán)境
contentTitle 狀態(tài)欄中的大標(biāo)題
contentText 狀態(tài)欄中的小標(biāo)題
contentIntent 點擊后將發(fā)送PendingIntent對象
說明:要是在Notification中加入圖標(biāo)结缚,在狀態(tài)欄和狀態(tài)條中顯示圖標(biāo)一定要用這個方法,否則報錯软棺!

  最后說一下NotificationManager類的常用方法:
         通過獲取系統(tǒng)服務(wù)來獲取該對象:            
            NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE) ;

** NotificationManager常用方法介紹:**
public void cancelAll() 移除所有通知 (只是針對當(dāng)前Context下的Notification)
public void cancel(int id) 移除標(biāo)記為id的通知 (只是針對當(dāng)前Context下的所有Notification)
public void** **notify(String tag ,int id, Notification notification) 將通知加入狀態(tài)欄, 標(biāo)簽為tag红竭,標(biāo)記為id
public void notify(int id, Notification notification) 將通知加入狀態(tài)欄,,標(biāo)記為id
下面看一下demo的效果圖:

Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png

源碼奉上:
在NotificationApp工程里面:
一喘落、在com.cn.notification.daming包下面NotificationMainActivity.java中的代碼:

    package com.cn.notification.daming;  
  
import android.app.Activity;  
import android.app.Notification;  
import android.app.NotificationManager;  
import android.app.PendingIntent;  
import android.content.Intent;  
import android.content.SharedPreferences;  
import android.media.RingtoneManager;  
import android.net.Uri;  
import android.os.Bundle;  
import android.preference.PreferenceManager;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
  
public class NotificationMainActivity extends Activity implements OnClickListener {  
private Button setNotificationSoundBtn = null;  
    private Button showNotificatioBtn = null;  
    private Button cancelNotificationBtn = null;  
    private Intent mIntent = null;  
    private PendingIntent mPendingIntent = null;  
    private Notification mNotification = null;  
    private NotificationManager mNotificationManager = null;  
      
    private static final int NOTIFICATION_STATE = 1;  
    private static final int RINGTONE_PICKED = 2;  
      
    private Uri notifiSounds = null;  
      
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
          
        mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);  
          
        setNotificationSoundBtn = (Button)findViewById(R.id.button0);  
        setNotificationSoundBtn.setOnClickListener(this);  
        showNotificatioBtn = (Button)findViewById(R.id.button1);  
        showNotificatioBtn.setOnClickListener(this);  
        cancelNotificationBtn = (Button)findViewById(R.id.button2);  
        cancelNotificationBtn.setOnClickListener(this);  
          
        mIntent = new Intent(this, ToNotificationActivity.class);  
        mPendingIntent = PendingIntent.getActivity(this, 0, mIntent, 0);  
          
        mNotification = new Notification();  
    }  
  
    public void onClick(View v) {  
        // TODO Auto-generated method stub  
        switch(v.getId()){  
            case R.id.button0:  
                 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);  
                 Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);  
                 // Allow user to pick 'Default'  
                 intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);  
                 intent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));  
                 // Show only ringtones  
                 intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);  
                 // Don't show 'Silent'  
                 intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);  
                 String notifi_sound = sharedPreferences.getString("notification_sounds", null);  
                 if(notifi_sound != null){  
                     intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse(notifi_sound));  
                 }  
                 // Launch!  
                 startActivityForResult(intent, RINGTONE_PICKED);  
                break;  
            case R.id.button1:  
                mNotification.icon = R.drawable.daming;  
                mNotification.tickerText = "大明ZeroSon Notification";  
                mNotification.sound = notifiSounds;  
                mNotification.defaults = Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS;  
                mNotification.flags = Notification.FLAG_INSISTENT ;   
                mNotification.setLatestEventInfo(this, "大明Notification", "This is Daming`s Notification Test!", mPendingIntent);  
                mNotificationManager.notify(NOTIFICATION_STATE, mNotification);  
                break;  
            case R.id.button2:  
                mNotificationManager.cancel(NOTIFICATION_STATE);  
                break;  
            default:break;  
        }  
    }  
      
    @Override  
    protected void onResume() {  
        super.onResume();  
    }  
  
    @Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);    
        SharedPreferences.Editor editor = sharedPreferences.edit();    
          
        if (resultCode != RESULT_OK) {  
            return;  
        }  
        switch (requestCode) {  
            case RINGTONE_PICKED: {  
                notifiSounds = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);  
                editor.putString("notification_sounds", notifiSounds.toString());    
                editor.commit();    
                break;  
            }  
            default: break;  
        }  
    }  
}  

二茵宪、在com.cn.notification.daming包下面ToNotificationActivity.java中的代碼:

package com.cn.notification.daming;  
  
import android.app.Activity;  
import android.content.SharedPreferences;  
import android.media.Ringtone;  
import android.media.RingtoneManager;  
import android.net.Uri;  
import android.os.Bundle;  
import android.preference.PreferenceManager;  
import android.widget.TextView;  
  
public class ToNotificationActivity extends Activity{  
  
    private TextView textview = null;  
      
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main1);  
          
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);    
              
        textview = (TextView)findViewById(R.id.textview);  
        String notificationsound = sharedPreferences.getString("notification_sounds", null);  
        if(notificationsound == null){  
            textview.setText("默認Notification聲音");  
        } else{  
            Ringtone ringtone =  RingtoneManager.getRingtone(ToNotificationActivity.this, Uri.parse(notificationsound));  
            String title = ringtone.getTitle(ToNotificationActivity.this);  
            textview.setText(title);  
        }  
    }  
}  

三、在layout下main.xml布局文件的代碼

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
    <TextView    
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"   
        android:text="@string/hello"  
        android:gravity="center"  
        android:layout_marginBottom="10dip"  
     />  
     <Button  
        android:id="@+id/button0"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="設(shè)置Notification的sounds"  
        android:layout_marginBottom="10dip"  
     />  
     <Button  
        android:id="@+id/button1"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="發(fā)送Notification"  
        android:layout_marginBottom="10dip"  
     />  
     <Button  
        android:id="@+id/button2"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:text="取消Notification"  
        android:layout_marginBottom="10dip"  
     />  
</LinearLayout>  

四瘦棋、在layout下main1.xml布局文件的代碼

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
    <TextView   
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"   
        android:gravity="center"  
        android:textSize="10pt"  
        android:text="大明原創(chuàng)"  
        android:layout_marginTop="10dip"  
        android:layout_marginBottom="10dip"  
     />  
    <TextView   
        android:id="@+id/textview"   
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"   
        android:gravity="center"  
        android:textSize="10pt"  
        android:layout_marginTop="10dip"  
        android:layout_marginBottom="10dip"  
     />  
</LinearLayout>  

五稀火、manifest.xml中的代碼:

<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
      package="com.cn.notification.daming"  
      android:versionCode="1"  
      android:versionName="1.0">  
    <uses-sdk android:minSdkVersion="8" />  
    <uses-permission android:name="android.permission.VIBRATE" />   
      
    <application android:icon="@drawable/icon" android:label="@string/app_name">  
        <activity android:name=".NotificationMainActivity"  
                  android:label="@string/app_name">  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity>  
        <activity android:name=".ToNotificationActivity"></activity>  
    </application>  
</manifest>  
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市赌朋,隨后出現(xiàn)的幾起案子凰狞,更是在濱河造成了極大的恐慌篇裁,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件赡若,死亡現(xiàn)場離奇詭異达布,居然都是意外死亡,警方通過查閱死者的電腦和手機逾冬,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進店門黍聂,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人身腻,你說我怎么就攤上這事产还。” “怎么了嘀趟?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵脐区,是天一觀的道長。 經(jīng)常有香客問我去件,道長坡椒,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任尤溜,我火速辦了婚禮倔叼,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘宫莱。我一直安慰自己丈攒,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布授霸。 她就那樣靜靜地躺著巡验,像睡著了一般。 火紅的嫁衣襯著肌膚如雪碘耳。 梳的紋絲不亂的頭發(fā)上显设,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天,我揣著相機與錄音辛辨,去河邊找鬼捕捂。 笑死,一個胖子當(dāng)著我的面吹牛斗搞,可吹牛的內(nèi)容都是我干的指攒。 我是一名探鬼主播,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼僻焚,長吁一口氣:“原來是場噩夢啊……” “哼允悦!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起虑啤,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤隙弛,失蹤者是張志新(化名)和其女友劉穎架馋,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體驶鹉,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡绩蜻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了室埋。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片办绝。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖姚淆,靈堂內(nèi)的尸體忽然破棺而出孕蝉,到底是詐尸還是另有隱情,我是刑警寧澤腌逢,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布降淮,位于F島的核電站,受9級特大地震影響搏讶,放射性物質(zhì)發(fā)生泄漏佳鳖。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一媒惕、第九天 我趴在偏房一處隱蔽的房頂上張望系吩。 院中可真熱鬧,春花似錦妒蔚、人聲如沸穿挨。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽科盛。三九已至,卻和暖如春菜皂,著一層夾襖步出監(jiān)牢的瞬間贞绵,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工恍飘, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留榨崩,地道東北人。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓常侣,卻偏偏與公主長得像蜡饵,于是被迫代替她去往敵國和親弹渔。 傳聞我的和親對象是個殘疾皇子胳施,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,871評論 2 354

推薦閱讀更多精彩內(nèi)容