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);
		}

	}

}

相关文章
相关标签/搜索