当前位置: 移动技术网 > 移动技术>移动开发>Android > Android中Notification通知用法详解

Android中Notification通知用法详解

2019年07月24日  | 移动技术网移动技术  | 我要评论

notification的作用

通知(notification)是android系统中比较有特色的一个功能。当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,就可以用通知来实现

用法

首先我们需要一个notificationmanager来对通知进行管理,可以调用getsystemservice()方法得到,方法接收一个字符串参数用于确定获取系统的哪个服务,这里我们传入notification_service。

notificationmanager manager=(notificationmanager) getsystemservice(notification_service);

接下来用一个builder构造器来创建notification对象

intent intent=new intent(this,notificationactivity.class);
        //用intent表现出我们要启动notification的意图
        pendingintent pi=pendingintent.getactivity(this,0,intent,0);
        //将intent对象传入pendingintent对象的getactivity方法中
        notificationmanager manager=(notificationmanager) getsystemservice(notification_service);
        notification notification=new notificationcompat.builder(this)
            .setcontenttitle("this is content title")
            //设置通知栏中的标题
            .setcontenttext("hello world!")
            //设置通知栏中的内容
            .setwhen(system.currenttimemillis())
            //设置通知出现的时间,此时为事件响应后立马出现通知
            .setsmallicon(r.mipmap.ic_launcher)
            //设置通知出现在手机顶部的小图标
            .setlargeicon(bitmapfactory.decoderesource(getresources(),r.mipmap.ic_launcher))
            //设置通知栏中的大图标
            .setcontentintent(pi)
            //将pendingintent对象传入该方法中,表明点击通知后进入到notificationactivity.class页面
            .setautocancel(true)
            //点击通知后,通知自动消失
            .setdefaults(notificationcompat.default_all)
            //默认选项,根据手机当前的环境来决定通知发出时播放的铃声,震动,以及闪光灯
            .setpriority(notificationcompat.priority_max)
            //设置通知的权重
            .build();
        manager.notify(1,notification);
        //用于显示通知,第一个参数为id,每个通知的id都必须不同。第二个参数为具体的通知对象

注意事项

通知属性定义以后,要通过notificationmanager对象的notify()方法来显示通知。
项目运行后,如果通知一直无法发出,那么请看看手机里面的“通知与状态栏”里面的“通知管理”。部分手机默认对app不允许通知,所以需要先打开允许通知,再运行项目,才能收到通知信息。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网