现在的位置: 首页 > 综合 > 正文

Android Notification学习

2017年10月23日 ⁄ 综合 ⁄ 共 1853字 ⁄ 字号 评论关闭

Notification是显示在屏幕上方状态栏中的信息,一般用来作通知和提醒的作用.

创建和显示一个Notification需要如下5步:

通过getSystemService()获得一个NotificationManager对象.

创建一个Notification对象,设置显示在屏幕上方状态栏中的提示消息和图片以及发出通知的时间

新版本中通过notification的内嵌类Builder可以非常方便的设置通知栏的信息

使用NotificationManager类的notify()显示Notification消息.(在这一步中需要指定标识Notification的唯一ID.这个ID对于同一个NotificationManager来说必须是唯一的,否则会覆盖相同ID的Notification)


api 11 版本之前:

//显示通知信息
	protected void showNotification() {
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//				Notification notification = new Notification(this,R.drawable.ic_launcher);
		Notification notification = new Notification(R.drawable.ic_launcher,"",System.currentTimeMillis() );
		PendingIntent contentIndent = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this,MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
		notification.setLatestEventInfo(MainActivity.this, "您的BMI值过高", "通知监督人", contentIndent);
		//加i是为了显示多条Notification
		notificationManager.notify(i,notification);
		i++;
	}

api版本之后:

protected void showNotification2() {
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Builder builder = new Notification.Builder(MainActivity.this);
		PendingIntent contentIndent = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this,MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
		builder . setContentIntent(contentIndent) .setSmallIcon(R.drawable.ic_launcher)//设置状态栏里面的图标(小图标)                     .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.i5))//下拉下拉列表里面的图标(大图标)        .setTicker("this is bitch!") //设置状态栏的显示的信息
	           .setWhen(System.currentTimeMillis())//设置时间发生时间
	           .setAutoCancel(true)//设置可以清除
	           .setContentTitle("This is ContentTitle")//设置下拉列表里的标题
	           .setContentText("this is ContentText");//设置上下文内容
		Notification notification = builder.getNotification();
		//加i是为了显示多条Notification
		notificationManager.notify(i,notification);
	}

抱歉!评论已关闭.