Android Notification的简略应用

Android Notification的简单应用

Notification是显示在手机状态栏的通知,手机状态栏位于手机屏幕的最上方,哪里一般显示了手机当前的网络状态、电池状态、时间等。Notification锁代表的是一种具有全局效果的通知,程序一般通过NotificationManager服务来发送Notification。


MainActivity.java

public class MainActivity extends Activity {
	final int  NOTIFICATION_ID=1;
	NotificationManager nm;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		
	}
	public void send(View view){
		Intent intent = new Intent(MainActivity.this,NextActivity.class);
		//PendingIntent里边封装了一个Intent,意味着要启动的界面
		PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
		Builder builder = new Notification.Builder(MainActivity.this);
		//设置打开该通知,该通知自动消失
		Notification notification = builder.setAutoCancel(true)
		//设置显示在状态栏的通知提示信息
		.setTicker("有新消息")
		//设置小通知图标
		.setSmallIcon(R.drawable.ic_launcher)
		//设置通知内容的标题
		.setContentTitle("通知的内容的标题")
		//设置通知的内容
		.setContentText("通知的内容。。。。。。。。。。。。")
		//设置使用系统默认的声音,默认LED灯
		.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS)
		//设置通知要启动的Intent
		.setContentIntent(pi)
		.build();
		
		//设置完毕,发送通知
		nm.notify(NOTIFICATION_ID, notification);
	}
	public void cancel(View view){
		//根据设置的ID取消通知
		nm.cancel(NOTIFICATION_ID);
	}
}
如果不想使用默认设置,也可以使用如下代码

		//设置自定义声音
		setSound((Uri.parse("file:///sdcard/click.mp3")));
		//设置自定义震动
		setVibrate(new long[]{0,50,100,150});

效果图:

Android Notification的简略应用


不知道大家是否有所疑问?AlertDialog.Builder为什么要写在内部类中呢?这是建造者模式(将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示,白话文:它的意思就是将一个对象和怎么构建这个对象分离开来,如果你想构建一个对象,你把这个消息告诉构建者,并且将自己对这个对象的各种要求告诉建造者,然后建造者根据这些要求进行捣鼓,然后,你所需要的一个对象就出来了。)更简单来说对象的表示较为干净,繁琐创建过程给别人做。

版权声明:本文为博主原创文章,未经博主允许不得转载。