概述
android 的消息通知還是很方便的援雇,它會出現(xiàn)在窗體的頂部,并給出提示椎扬。常見的短信就是這樣的通知方式惫搏。本文我們嘗試實(shí)現(xiàn)一個(gè)這樣的演示。
演示截圖:
實(shí)現(xiàn)步驟:
-
獲得NotificationManager 對象盗舰,這是一個(gè)通知管理器晶府。我們在窗體里調(diào)用方法獲得
NotificationManager manager =
(NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE);getSystemService是獲得系統(tǒng)服務(wù)的方法。android以服務(wù)的形式提供給用戶操作接口钻趋。也就是說,我們要想操作 通知相關(guān)的操作接口剂习,就先獲得系統(tǒng)提供的 “通知管理器”
NotificationManager 對象就是一個(gè)服務(wù)管理器了蛮位。
-
構(gòu)建一個(gè)Notification 對象,這個(gè)Notification 對象描述了:通知的標(biāo)題和內(nèi)容鳞绕,通知要調(diào)用的窗體失仁。
//構(gòu)建一個(gè)通知對象,指定了 圖標(biāo)们何,標(biāo)題萄焦,和時(shí)間 Notification notification = new Notification(R.drawable.icon, "通知", System.currentTimeMillis()); //設(shè)定事件信息 notification.setLatestEventInfo(getApplicationContext(), "通知標(biāo)題", "通知顯示的內(nèi)容", pendingIntent); notification.flags|=Notification.FLAG_AUTO_CANCEL; //自動終止 notification.defaults |= Notification.DEFAULT_SOUND; //默認(rèn)聲音
其中pendingIntent對象 是一個(gè)跳轉(zhuǎn)intent,當(dāng)提示后,點(diǎn)擊在消息提示欄的 “通知”時(shí)拂封,能打開一個(gè)窗體activity
PendingIntent pendingIntent = PendingIntent.getActivity(
ActNotifyDemo.this,
0,
new Intent(ActNotifyDemo.this,ActNotifyDemo.class), //指定一個(gè)跳轉(zhuǎn)的intent
0
);
實(shí)際上是PendingIntent 包含(封裝)了一個(gè)跳轉(zhuǎn)的 intent對象茬射。
3.調(diào)用NotificationManager.notify方法發(fā)起通知,發(fā)起后的通知就會在消息欄提示冒签。
代碼如下:
public class ActNotifyDemo extends Activity {
Button _btn1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_btn1 = (Button)findViewById(R.id.button1);
_btn1.setOnClickListener(new OnClickListener(){
//觸發(fā)通知
public void onClick(View arg0) {
//獲得通知管理器
NotificationManager manager = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
//構(gòu)建一個(gè)通知對象
Notification notification = new Notification(R.drawable.icon,
"通知", System.currentTimeMillis());
PendingIntent pendingIntent = PendingIntent.getActivity(
ActNotifyDemo.this,
0,
new Intent(ActNotifyDemo.this,ActNotifyDemo.class),
0
);
notification.setLatestEventInfo(getApplicationContext(),
"通知標(biāo)題",
"通知顯示的內(nèi)容",
pendingIntent);
notification.flags|=Notification.FLAG_AUTO_CANCEL; //自動終止
notification.defaults |= Notification.DEFAULT_SOUND; //默認(rèn)聲音
manager.notify(0, notification);//發(fā)起通知
}
});
}
}