Notification與NotificationManager

Notification是要發出的通知,NotificationManager用來發出和取消通知 java


大概的步驟: android

1.得到系統服務NotificationManager app

2.實例化Notification 並設置其屬性 ide

3.調用setLatestEventInfo方法在視圖中設置圖標和時間(這個方法在Android 3.0被棄用) 測試

4.最後調用NotificationManager的notify方法 發出通知 this

package com.example.notification01;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;

public class MainActivity extends Activity {
	private Button btn1, btn2;
	private Notification n;
	private NotificationManager nm;
	private static final int ID = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		btn1 = (Button) findViewById(R.id.button1);
		btn1.setOnClickListener(new sendListener());

		btn2 = (Button) findViewById(R.id.button2);
		btn2.setOnClickListener(new cancelListener());

		// 1.得到系統服務NotificationManager
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		// 2.實例化Notification 並設置其屬性
		n = new Notification();
		n.icon = R.drawable.ic_launcher;
		n.tickerText = "Notification測試";
		n.when = System.currentTimeMillis();
	}

	public class sendListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(MainActivity.this, MainActivity.class);
			PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0,
					intent, 0);

			// 3.調用setLatestEventInfo方法在視圖中設置圖標和時間(這個方法在Android 3.0被棄用)
			n.setLatestEventInfo(MainActivity.this, "Title", "Content", pi);
			// 4.最後調用NotificationManager的notify方法 發出通知
			nm.notify(ID, n);
		}

	}

	public class cancelListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// 取消通知
			nm.cancel(ID);
		}

	}

}

相關文章
相關標籤/搜索