首先新建一個Android工程
然後編輯main.xml
代碼如下:
[xhtml]
<?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"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send"
android:id="@+id/button"
/>
</LinearLayout>
再編輯strings.xml
[xhtml]
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">通知</string>
<string name="app_name">狀態欄通知</string>
<string name="send">發送通知</string>
</resources>
然後就是對其Notification進行處理
下面來看一下創建並顯示一個Notification的步驟。創建和顯 示一個Notification需要如下5步:
1. 通過getSystemService方法獲得一個NotificationManager對象。
2. 創建一個Notification對象。每一個Notification對應一個Notification對象。在這一步需要設置顯示在屏幕上方狀態欄的通知消息、通知消息前方的圖像資源ID和發出通知的時間。一般為當前時間。
3. 由於Notification可以與應用程序脫離。也就是說,即使應用程序被關閉,Notification仍然會顯示在狀態欄 中。當應用程序再次啟動後,又可以重新控制這些Notification。如清除或替換它們。因此,需要創建一個PendingIntent對象。該對象由Android系統負責維護,因此,在應用程序關閉後,該對象仍然不會被釋放。
4. 使用Notification類的setLatestEventInfo方法設置Notification的詳細信息。
5. 使用NotificationManager類的notify方法顯示Notification消息。在這一步需要指定標識Notification的唯一ID。這個ID必須相對於同一個NotificationManager對象是唯一的,否則就會覆蓋相同ID的Notificaiton。
心動不如行動,下面我們來演練一下如何在狀 態欄顯示一個Notification,代碼如下:
[java]
package com.cayden.notification;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* @author 崔冉
*
*/
public class NotificationActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button=(Button)this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/**
* 獲取通知管理器
*/
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int icon=android.R.drawable.sym_action_email;
long when=System.currentTimeMillis();
/**
* 新建一個通知指定圖標和標題
*/
Notification notification=new Notification(icon,null,when);
notification.defaults=Notification.DEFAULT_SOUND;//發出默認聲音
PendingIntent contenIntent=PendingIntent.getActivity(NotificationActivity.this, 0, null, 0);
notification.setLatestEventInfo(NotificationActivity.this, "開會通知", "今天下午四點半在512開會!", contenIntent);
notificationManager.notify(0, notification);//發送通知
}
});
}
}
運行效果如圖所示:
點擊發送通知按鈕
後的效果
在左上角多出一個郵件符號.
然後用鼠標選中往下拖