1. 通知的使用场合

  当某个应用程序希望向用户发出一些提示信息,而该应用程序又不在前台运行时,就可以借助通知来实现。发出一条通知后,手机最上方的状态栏中会显示一个通知的图标,下拉状态栏后可以看到通知的详细内容。
2. 通知的创建步骤
  (1)获取NotificationManager实例,可以通过调用Conten的getSystenService()方法得到,getSystemService()方法接收一个字符串参数用于确定获取系统的哪个服务, 这里我们传入Context.NOTIFICATION_SERVICE 即可。获取NotificationManager实例如下:

  NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

  (2)创建Notification对象,该对象用于存储通知的各种所需信息,我们可以使用它的有参构造函数来创建。构造函数有三个参数,第一个参数指定通知图标,第二个参数用于指定通知的ticker 内容,当通知刚被创建的时候,它会在系统的状态栏一闪而过,属于一种瞬时的提示信息。第三个参数用于指定通知被创建的时间,以毫秒为单位,当下拉系统状态栏时,这里指定的时间会显示在相应的通知上。创建一个Notification 对象可以写成:

  Notification notification = new Notification(R.drawable.ic_launcher,"This is a ticker

  (3)调用Notification的setLatestEventIfo()方法对通知的布局进行设定,这个方法接收四个参数,第一个参数是Context。第二个参数用于指定通知的标题内容,下拉系统状态栏就可以看到这部分内容。第三个参数用于指定通知的正文内容,同样下拉系统状态栏就可以看到这部分内容。第四个参数用于指定实现通知点击事件的PendingIntent对象,如果暂时用不到可以先传入null。因此,对通知的布局进行设定就可以写成:

  notification.setLatestEventInfo(context, "This is content title", "This iscontent text", null);
  (4)调用NotificationManager的notify()方法显示通知。notify()方法接收两个参数,第一个参数是id,要保证为每个通知所指定的id 都是不同的。第二个参数则是Notification 对象,这里直接将我们刚刚创建好的Notification 对象传入即可。显示一个通知就可以写成:

  manager.notify(1, notification);
3.代码示例

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button 
        android:id="@+id/send_notice"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send notice"
        />
    
</LinearLayout>
布局

相关文章:

  • 2022-12-23
  • 2021-11-17
  • 2021-06-27
  • 2021-04-10
  • 2022-12-23
  • 2021-04-08
猜你喜欢
  • 2022-02-06
  • 2021-12-23
  • 2022-12-23
  • 2021-07-26
  • 2021-06-10
  • 2021-09-22
  • 2021-12-27
相关资源
相似解决方案