Android入門筆記之狀態欄通知

<1>簡介

Android系統的狀態欄(Status Bar)中有一個創新UI設計,這就是可以下拉的通知提示。當系統有一些消息要通知用戶時,例如,收到短信、電子郵件、有未接來電時,都會把信息作爲通知(Notification)發送給用戶。

Status Bar 增加了一個圖標到系統狀態欄中,還有文本信息(可以不選),增加Notification信息到Notification窗口。你還可以安裝Notification利用的聲音,震動,設備上閃關燈來提醒用戶。 

Notification與Toast都可以起到通知、提醒的作用。但它們的實現原理和表現形式卻完全不一樣。

Toast其實相當於一個組件(Widget)。有些類似於沒有按鈕的對話框。而Notification是顯示在屏幕上方狀態欄中的信息。

Notification需要用NotificationManager來管理,而Toast只需要簡單地創建Toast對象即可。

 

<2>關鍵步驟

Noitficion的構造函數已經過時。      The Notification.Builder hasbeen added to make it easier to construct Notifications.

 

創建 status bar notification:

1.NotificationManager得到一個參考:

NotificationManager mNotificationManager  = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

 

2.創建一個Notification對象。每一個Notification對應一個Notification對象。在這一步需要設置顯示在屏幕上方狀態欄的通知消息、通知消息前方的圖像資源ID和發出通知的時間。

       int icon = R.drawable.notification_icon; //顯示在屏幕上方狀態欄的圖標  

CharSequence tickerText = "Hello";     //顯示在屏幕上方狀態欄的通知消息  

long when = System.currentTimeMillis(); //發出通知的時間  

Notification notification = new Notification(icon, tickerText, when);  

       3.定義的信息和PendingIntent通知:

PendingIntent封裝了一個Intent,當用戶點擊通知後會跳到對應的Activity。

PendingIntent對象由Android系統負責維護,因此,在應用程序關閉後,該對象仍然不會被釋放。 

<3>出現的問題

       Noitficion有些方法已經不被支持,使用Noitficion.builder來創建,api最低要求是16。

<4>代碼及解釋

      

StatusBarActivity.java:

package com.ui.status;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;

import com.activity.firstActivity;
import com.test.R;

public class StatusBarActivity extends Activity{
	/**   
	 * @ProjectName:  [androidtest] 
	 * @Package:      [com.ui.status.StatusBarActivity.java]  
	 * @ClassName:    [StatusBarActivity]   
	 * @Description:    
	 * @Author:       [gmj]   
	 * @CreateDate:   [2013-9-6 下午10:12:54]   
	 * @Version:      [v1.0] 
	 */
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		/*Notification notification = new Notification.Builder(this)
									.setContentText("my message")
									.setSmallIcon(R.drawable.img1)
									.setContentTitle("new mail")
									.build();		
		*/
		Notification notification = new Notification(R.drawable.img1 , "my message" ,System.currentTimeMillis());
		
		
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		Intent notificationIntent = new Intent(StatusBarActivity.this , firstActivity.class);
		PendingIntent pedingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		notification.setLatestEventInfo(this , "have a message" , "hhhhhhh" , pedingIntent);
		
		notificationManager.notify(R.drawable.img2 , notification);
	}
}


發佈了29 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章