zoukankan      html  css  js  c++  java
  • android通知的基本用法

        在读《第一行代码》时发现书上关于通知的讲解所使用的方法已经过时了,新版本陆续不支持了。

        新的方法如下:

          1、首先需要创建一个NotificationManager类的对象来对通知进行管理,通过调用Context的getSystemService()方法获取到。具体代码如下:

             NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

          2、创建一个Notification对象来存储通知所需的各种信息

                          Notification.Builder builder = new Notification.Builder(MainActivity.this);

                 builder.setContentTitle("我是通知");

                    builder.setContentText("我是通知内容");

                     builder.setContentInfo("我是通知附加信息" );
              builder.setSmallIcon(R.mipmap.ic_launcher);
              notification = builder.build(); //获取notification的实例
        
         3、最后调用NotificationMannager的notify()方法让通知可以显示出来
            
    notificationManager.notify(1, notification); //第一个参数是通知的Id,不同通知Id不能相同

        4.怎样给自己的通知添加响应事件呢?
            这需要使用到PendingIntent类,有点类似于Intent,代码如下:
                
    Intent intent = new Intent(MainActivity.this, NotificationActivity.class);

                PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
                builder.setContentIntent(pendingIntent);
     
    5、上述步骤成功后发现点击通知栏后,通知栏并没有消失,这是因为通知栏是需要人为调用方法去取消的,代码如下:
          
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(1);//传入的参数正是之前给通知指定的Id











































  • 相关阅读:
    批量数据导入数据库方法
    Remoting简单实践
    js面向对象继承
    Linq实现t-Sql的各种连接
    数据库树状结构的关系表的删除方案
    记录一次SQL查询语句
    mvc请求过程总结
    T-sql表表达式
    各个浏览器的兼容问题及样式兼容处理(不定期补充)
    vue.js 键盘enter事件的使用
  • 原文地址:https://www.cnblogs.com/keqi-Android/p/5890237.html
Copyright © 2011-2022 走看看