通知—Notifications

通知(Notification)是Android系统中常用的一种通知方式,当手机有未接电话的时候,Android设备顶部状态栏里就会有提示小图标。当下拉状态栏时可以查看这些快讯。

下面通过一个例子具体展示通知的基本使用方法。

main.xml

1.   <?xml version="1.0" encoding="utf-8"?>

2.   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

3.   android:orientation="vertical"

4.   android:layout_width="fill_parent"

5.   android:layout_height="fill_parent">

6.   <TextView 

7.   android:layout_width="fill_parent"

8.   android:layout_height="wrap_content"

9.   android:text="通知示例"/>

10.  <Button android:id="@+id/button1"

11.  android:layout_height="wrap_content"

12.  android:layout_width="fill_parent"

13.  android:text="添加通知"/>

14.  </LinearLayout>

主界面就放了一个提示文本textview和一个触发添加通知的按钮。

程序Java代码如下。

MyNotify.java

1.   public class MyNotify extends Activity {

2.   Button btn1;

3.   @Override

4.   public void onCreate(Bundle savedInstanceState) {

5.   super.onCreate(savedInstanceState);

6.   setContentView(R.layout.main);

7.   btn1 = (Button)findViewById(R.id.button1);

8.   btn1.setOnClickListener(new OnClickListener(){

9.   public void onClick(View arg0) {

10.  NotificationManager manager = (NotificationManager) getSystemService( Context.
    NOTIFICATION_SERVICE);

第10行获得NotificationManager 对象,这是个通知管理器。

11.  Notification notification = new Notification(R.drawable.icon, "我的通知", System.
    currentTimeMillis());

第11行我们构建了一个新通知对象,并指定了图标、标题和触发时间。

12.  PendingIntent pendingIntent = PendingIntent.getActivity(MyNotify.this,0,new     Intent(MyNotify.this,MyNotify.class),0);

第12行中pendingIntent对象是一个跳转Intent,当用户单击通知提示栏“我的通知”时打开一个Activity,在这个例子里我们打开MyNotify。

13.  notification.setLatestEventInfo(getApplicationContext(),"通知标题","这是一个新的通           知",pendingIntent);

第13行设定下拉通知栏时显示通知的标题和内容信息。

14.  notification.flags|=Notification.FLAG_AUTO_CANCEL;

15.  notification.defaults |= Notification.DEFAULT_SOUND;

第14行设定通知当用户单击后自动消失。

第15行设定通知触发时的默认声音。

16.  manager.notify(0, notification);

第16行调用通知管理器的Notify方法发起通知。

17.  }});

18.  }}

第10行获得NotificationManager 对象,这是个通知管理器。

第11行我们构建了一个新通知对象,并指定了图标、标题和触发时间。

第12行中pendingIntent对象是一个跳转Intent,当用户单击通知提示栏“我的通知”时打开一个Activity,在这个例子里我们打开MyNotify。

第13行设定下拉通知栏时显示通知的标题和内容信息。

第14行设定通知当用户单击后自动消失。

第15行设定通知触发时的默认声音。

第16行调用通知管理器的Notify方法发起通知。

图10-21~图10-23所示是通知示例的效果图。

      

▲图10-21  通知示例主界面                                ▲图10-22  单击添加通知后的效果图

 

▲图10-23  拉下通知栏后看到的通知信息

原文地址:https://www.cnblogs.com/zhoujn/p/4311643.html