今天在学习Notification时同时参考了一些相关的博客,现在结合自身学习实际来总结一下。

在使用手机时,当有未接来电或者短消息时,通常会在手机屏幕上的状态栏上显示。而在Android中有提醒功能的也可以用AlertDialog,但是当使用AlertDialog 的时候,用户正在进行的操作将会被打断。因为当前焦点被AlertDialog得到。我们可以想像一下,当用户打游戏正爽的时候,这时候来了一条短信。如果这时候短信用AlertDialog提醒,用户必须先去处理这条提醒,从而才能继续游戏。用户可能会活活被气死。而使用Notification就不会带来这些麻烦事,用户完全可以打完游戏再去看这条短信。所以在开发中应根据实际需求,选择合适的控件。

 

状态栏通知涉及到两个类,一是Notification,它代表一个通知;另一个是NotificationManager,它是用于发送Notification的系统服务。

使用状态栏通知一般有4个步骤:

1、  通过getSystemService()方法获取NotificationManager服务。

2、  创建一个Notification对象,并为其设置各种属性。

3、  为Notification对象设置事件信息。

4、  通过NotificationManager类的notify()方法将通知发送到状态栏。

下面我们通过一个例子来实际操作一下:

首先是布局文件new_main.xml的使用:

 1 <?xml version="1.0" encoding="utf-8"?>  
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
 3     android:layout_width="fill_parent"  
 4     android:layout_height="fill_parent"  
 5     android:orientation="vertical" >  
 6   
 7     <Button  
 8         android:id="@+id/button1"  
 9         android:text="发送消息"  
10         android:layout_width="wrap_content"  
11         android:layout_height="wrap_content" />  
12   
13     <Button  
14         android:id="@+id/button2"  
15         android:text="清空消息"  
16         android:layout_width="wrap_content"  
17         android:layout_height="wrap_content" />  
18   
19 </LinearLayout>  
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
  • 2021-12-02
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-06
  • 2021-10-25
  • 2021-12-18
  • 2021-09-19
  • 2021-06-25
  • 2022-12-23
相关资源
相似解决方案