Android-60-Notification 通知栏的简略使用

Android---60---Notification 通知栏的简单使用

Notification是显示在手机状态栏的通知 


通过Notification.Builder类创建Notification对象。

Notification.Builder常用方法:

setDefaults ():设置通知LED灯、音乐、振动等

setAutoCancle():设置点击通知后,状态栏自动删除通知

setContentTitle():设置通知标题

setContentText():设置通知内容

setSmallcon():设置小图标

setLargecon():设置大图标

setTick():设置通知在状态栏的提示为本

setContentIntent ():设置点击通知后将要启动的程序组件对应的PendingIntent

setWhen ():设置通知发布的时间

 

步骤:

1.调用getSystemService(NOTIFICATION_SERVICE)方法获取系统的NotificationManager方法

manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


2.创建一个Notification.Builder对象

Notification.Builder builder = new Notification.Builder(MainActivity.this);


3.为builder设置各种属性

4.创建一个Notification对象
Notification notification = builder.build();

5.通过NotificationManager的notify方法发送Notification 
manager.notify(ID, notification);

 

Demo:

 

Activity:

public class MainActivity extends Activity {

	Button send, del;
	NotificationManager manager;
	int ID = 0x123;

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

		send = (Button) findViewById(R.id.send);
		del = (Button) findViewById(R.id.del);

		manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(MainActivity.this, other.class);
				PendingIntent pi = PendingIntent.getActivity(MainActivity.this,
						0, intent, 0);

				Notification.Builder builder = new Notification.Builder(
						MainActivity.this);
				builder
				// Notification notification = new
				// Notification.Builder(MainActivity.this)

				// 设置打开通知,该通知取消
				.setAutoCancel(true)
				// 设置通知提示信息
						.setTicker("有新消息")
						// 设置通知的图标
						.setSmallIcon(R.drawable.pig)
						// 设置通知的标题
						.setContentTitle("不好了!!!")
						// 设置通知的内容
						.setContentText("你家猪跑了")
						// 设置使用系统默认的声音、LED
						.setDefaults(
								Notification.DEFAULT_LIGHTS
										| Notification.DEFAULT_SOUND)
						// 设置通知发布时间
						.setWhen(System.currentTimeMillis())
						// 设置将要启动的活动
						.setContentIntent(pi).build();

				Notification notification = builder.build();

				manager.notify(ID, notification);

			}
		});

		del.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				manager.cancel(ID);
			}
		});
	}
}


 

 

Android-60-Notification 通知栏的简略使用

 

点击发送通知:

 

Android-60-Notification 通知栏的简略使用


 

 

点击该通知会跳转到另一个活动:

 

Android-60-Notification 通知栏的简略使用