1. 程式人生 > >android之【本地通知Notification】

android之【本地通知Notification】

public class NotificationTest extends Activity
{
	static final int NOTIFICATION_ID = 0x1123;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//獲取應用介面中的Button物件
		Button bn = (Button) findViewById(R.id.bn);
		//為按鈕的單擊事件繫結事件監聽器
		bn.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View source)
			{
				//建立一個啟動其他Activity的Intent
				Intent intent = new Intent(NotificationTest.this
					, OtherActivity.class);
				PendingIntent pi = PendingIntent.getActivity(NotificationTest.this
					, 0, intent , 0);
				//建立一個Notification
				Notification notify = new Notification();
				//為Notification設定圖示,該圖示顯示在狀態列
				notify.icon = R.drawable.notify;
				//為Notification設定文字內容,該文字會顯示在狀態列
				notify.tickerText = "啟動其他Activity的通知";
				//為Notification設定傳送時間
				notify.when = System.currentTimeMillis();
				//為Notification設定聲音
				notify.defaults = Notification.DEFAULT_SOUND;
				//為Notification設定預設聲音、預設振動、預設閃光燈
				notify.defaults = Notification.DEFAULT_ALL;
				//設定事件資訊
				notify.setLatestEventInfo(NotificationTest.this, "普通通知",
					"點選檢視", pi);
				//獲取系統的NotificationManager服務
				NotificationManager notificationManager = (NotificationManager) 
					getSystemService(NOTIFICATION_SERVICE);
				//傳送通知
				notificationManager.notify(NOTIFICATION_ID, notify);
			}
		});
		
		//取消通知
		Button del = (Button)findViewById(R.id.del);
		del.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				//獲取系統的NotificationManager服務
				NotificationManager notificationManager = (NotificationManager) 
					getSystemService(NOTIFICATION_SERVICE);
				//取消通知
				notificationManager.cancel(NOTIFICATION_ID);
			}
		});
	}
}