您的位置:首页 > 移动开发 > Android开发

android发通知NotificationManager和Notification的详解

2015-09-10 14:33 417 查看
下面对Notification类中的一些常量,字段,方法简单介绍一下:

常量:

DEFAULT_ALL 使用所有默认值,比如声音,震动,闪屏等等

DEFAULT_LIGHTS 使用默认闪光提示

DEFAULT_SOUNDS 使用默认提示声音

DEFAULT_VIBRATE 使用默认手机震动

【说明】:加入手机震动,一定要在manifest.xml中加入权限:

<uses-permission android:name="android.permission.VIBRATE" />

以上的效果常量可以叠加,即通过

notification.defaults =DEFAULT_SOUND|DEFAULT_VIBRATE;

notification.defaults |= DEFAULT_SOUND (最好在真机上测试,震动效果模拟器上没有)

//设置flag位

FLAG_AUTO_CANCEL 该通知能被状态栏的清除按钮给清除掉

FLAG_NO_CLEAR 该通知能被状态栏的清除按钮给清除掉

FLAG_ONGOING_EVENT 通知放置在正在运行

FLAG_INSISTENT 是否一直进行,比如音乐一直播放,知道用户响应

常用字段:

contentIntent 设置PendingIntent对象,点击时发送该Intent

defaults 添加默认效果

flags 设置flag位,例如FLAG_NO_CLEAR等

icon 设置图标

sound 设置声音

tickerText 显示在状态栏中的文字

when 发送此通知的时间戳

public static void notice(String text) {
if (!TextUtils.isEmpty(text)) {
Context context = APPContext.getInstance();
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.icon = R.mipmap.ic_launcher;// 设置通知的图标
notification.tickerText = text; // 显示在状态栏中的文字
notification.when = System.currentTimeMillis(); // 设置来通知时的时间
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults = Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE;//将使用默认的声音和振动来提醒用户

String appName = context.getResources().getString(R.string.app_name); Intent intent = new Intent(context, HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); //这里需要设置Intent.FLAG_ACTIVITY_NEW_TASK属性
PendingIntent pend = PendingIntent.getActivity(context, R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//这里必需要用setLatestEventInfo(上下文,标题,内容,PendingIntent)不然会报错.
notification.setLatestEventInfo(context, appName, text, pend); manager.notify(getInstance().getIndex(), notification);
//这里发送通知(消息ID,通知对象)
}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: