Android的消息通知--Notification
发布日期:2021-06-30 21:21:40 浏览次数:3 分类:技术文章

本文共 2373 字,大约阅读时间需要 7 分钟。

    可以用Activity和Service来开端消息通知,两者的差别在于一个是在前台触发,一个是后台办事触发。

  要应用消息通知,必必要用到两个类:
NotificationManager和Notification
,其他NotificationManager的初始化是用getSystemService办法,并且经由过程notify办法来向android体系发送消息栏通知和显示。

代码如下:

有版本层次  

package com.li.tozhilai;import android.app.Activity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.view.View;public class MainActivity extends Activity {	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);	}	//android  版本 2 使用的api	public void showNotification(View v){		//获取系统服务		NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);		/**		 * icon  表示图片的意思		 * tickerText 标示文本		 * when 是吗时候提示该消息		 */		//notification  是有俩部分组成的  第一部分是手机头部的显示    第二部分是当吧头部下拉时显示内容		Notification notification = new Notification(R.drawable.ic_launcher, "音乐播放器", System.currentTimeMillis());		/**		 * context  表示的context		 * contentTitle  内容标题		 * contentText	 内容文本		 * contentIntent 点击通知栏上的时候决定要跳转的意图		 */		//PendingIntent.FLAG_ONE_SHOT该参数表示标题栏上值显示一次		Intent intents=new Intent(this,MainActivity.class);		PendingIntent intent = PendingIntent.getActivity(this, 0, intents,PendingIntent.FLAG_ONE_SHOT);		//第二部分是当吧头部下拉时显示内容		notification.setLatestEventInfo(this,										"标题", 										"文本内容", intent);		/**		 * id :来标示当前的提示		 * notification:用来封装了提示的内容		 */				manager.notify(0, notification);//用来提示用户的	}	//点击取消提示框	public void clickCloseShow(View v){		//获取系统服务		NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);		//manager.cancel(id);该方法指定取消id为及的提示框		manager.cancelAll();//表示取消全部的提示框	}	//android  版本 4 使用的api	public void showNotificationBy4(View v){		//拿到系统服务		NotificationManager manager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);		Notification notification = new Notification();		notification.icon=R.drawable.ic_launcher;//设置图片		notification.tickerText="标题文本";//标题文本		notification.when=System.currentTimeMillis();//设置显示时间		Intent intent = new Intent(this,MainActivity.class);		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);		notification.setLatestEventInfo(this, "音乐", "正在播放", contentIntent);		manager.notify(1, notification);	}}

转载地址:https://liwangjiang.blog.csdn.net/article/details/79751547 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android的Menu使用
下一篇:Android服务器的使用(Service)

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月11日 02时00分03秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章