Android中Notification詳解【android進化三十五】 – Android移動開發技術文章_手機開發 Android移動開發教學課程

 下面來談談notification,這個notification一般用在電話,短信,郵件,鬧鐘鈴聲,在手機的狀態欄上就會出現一個小圖標,提示用戶處理這個快訊,這時手從上方滑動狀態欄就可以展開並處理這個快訊。發現這個功能特別好用,所以我就根據我的理解來談談。摘自幫助文檔 :  notification類表示一個持久的通知,將提交給用戶使用NotificationManager。已添加的Notification.Builder,使其更容易構建通知。notification是一種讓你的應用程序在沒有開啟情況下或在後臺運行警示用戶。它是看不見的程序組件(Broadcast Receiver,Service和不活躍的Activity)警示用戶有需要註意的事件發生的最好途徑。
    先來區分以下狀態欄和狀態條的區別:

    1、狀態條就是手機屏幕最上方的一個條形狀的區域;

          在狀態條有好多信息量:比如usb連接圖標,手機信號圖標,電池電量圖標,時間圖標等等;

    2、狀態欄就是手從狀態條滑下來的可以伸縮的view;

          在狀態欄中一般有兩類(使用FLAG_標記):

          (1)正在進行的程序;

          (2)是通知事件;

 

     大概來描述創建一個Notification傳送的信息有:

    1、一個狀態條圖標;

    2、在拉伸的狀態欄窗口中顯示帶有大標題,小標題,圖標的信息,並且有處理該點擊事件:比如調用該程序的入口類;

    3、閃光,LED,或者震動;

 

      快速創建一個Notification的步驟簡單可以分為以下四步:

      第一步:通過getSystemService()方法得到NotificationManager對象;

      第二步:對Notification的一些屬性進行設置比如:內容,圖標,標題,相應notification的動作進行處理等等;

      第三步:通過NotificationManager對象的notify()方法來執行一個notification的快訊;

      第四步:通過NotificationManager對象的cancel()方法來取消一個notificatioin的快訊;

 

     下面對Notification類中的一些常量,字段,方法簡單介紹一下:

     常量:

        DEFAULT_ALL                  使用所有默認值,比如聲音,震動,閃屏等等

        DEFAULT_LIGHTS            使用默認閃光提示

        DEFAULT_SOUNDS         使用默認提示聲音

        DEFAULT_VIBRATE         使用默認手機震動 

      【說明】:加入手機震動,一定要在manifest.xml中加入權限:

                         <uses-permission android:name="android.permission.VIBRATE" />

        以上的效果常量可以疊加,即通過

                mNotifaction.defaults =DEFAULT_SOUND  |  DEFAULT_VIBRATE ;  

            或mNotifaction.defaults |=DEFAULT_SOUND   (最好在真機上測試,震動效果模擬器上沒有)

 

        //設置flag位

           FLAG_AUTO_CANCEL          該通知能被狀態欄的清除按鈕給清除掉

        FLAG_NO_CLEAR                  該通知能被狀態欄的清除按鈕給清除掉

        FLAG_ONGOING_EVENT      通知放置在正在運行

        FLAG_INSISTENT                    是否一直進行,比如音樂一直播放,知道用戶響應

 

      常用字段:

           contentIntent                  設置PendingIntent對象,點擊時發送該Intent

           defaults                             添加默認效果

           flags                                  設置flag位,例如FLAG_NO_CLEAR等

           icon                                  設置圖標

           sound                                設置聲音

           tickerText                        顯示在狀態欄中的文字

           when                                發送此通知的時間戳

 

Notification.build構造Notification方法介紹:   

     void setLatestEventInfo(Context context , CharSequencecontentTitle,CharSequence  contentText,PendingIntent contentIntent)  

          

        功能: 顯示在拉伸狀態欄中的Notification屬性,點擊後將發送PendingIntent對象

        參數: context             上下文環境

                      contentTitle      狀態欄中的大標題

                      contentText      狀態欄中的小標題

                      contentIntent    點擊後將發送PendingIntent對象

      說明:要是在Notification中加入圖標,在狀態欄和狀態條中顯示圖標一定要用這個方法,否則報錯!

 

      最後說一下NotificationManager類的常用方法:

             通過獲取系統服務來獲取該對象:           

                NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE) ;

 

      NotificationManager常用方法介紹:

               public  void cancelAll()                                                          移除所有通知 (隻是針對當前Context下的Notification)

               public  void cancel(int id)                                                      移除標記為id的通知 (隻是針對當前Context下的所有Notification)

               public  void notify(String tag ,int id, Notification notification) 將通知加入狀態欄, 標簽為tag,標記為id

               public  void notify(int id, Notification notification)                   將通知加入狀態欄,,標記為id

 

     下面看一下demo的效果圖:

                              

                                                    圖(1)                                                                                                                                  圖(2)

 

                                                     

                                                                   圖(3)                                                                                                                         圖(4)                                    

 

                           

                                             圖(5)

 

 源碼奉上:

在NotificationApp工程裡面:

一、在com.cn.notification.daming包下面NotificationMainActivity.java中的代碼:

www.aiwalls.com
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; 
        } 
    } 

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

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="設置Notification的sounds" 
        android:layout_marginBottom="10dip" 
     /> 
     <Button 
        android:id="@+id/button1" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="發送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> 
<?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="設置Notification的sounds"
     android:layout_marginBottom="10dip"
  />
  <Button
     android:id="@+id/button1"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="發送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="大明原創" 
        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> 
<?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="大明原創"
     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> 

發佈留言