Notification可以在屏幕最顶部的状态栏上显示一个图标通知(QQ用的就是这个),通知的同时可以播放声音,以及振动提示用户,点击通知还可以返回指定的Activity.
今天例子的效果图:
![](http://www.pocketdigi.com/wp-content/uploads/2010/09/notification.jpg)
布局main.xml:
01 | <?xml version= "1.0" encoding= "utf-8" ?> |
03 | android:orientation= "vertical" |
04 | android:layout_width= "fill_parent" |
05 | android:layout_height= "fill_parent" |
07 | <Button android:id= "@+id/bt1" |
08 | android:layout_height= "wrap_content" |
09 | android:layout_width= "fill_parent" |
10 | android:text= "Notification测试" |
12 | <Button android:id= "@+id/bt2" |
13 | android:layout_height= "wrap_content" |
14 | android:layout_width= "fill_parent" |
15 | android:text= "清除Notification" |
就两个按钮,一个添加Notification,一个删除Notification
01 | package com.pocketdigi.Notification; |
03 | import android.app.Activity; |
04 | import android.app.Notification; |
05 | import android.app.NotificationManager; |
06 | import android.app.PendingIntent; |
07 | import android.content.Intent; |
08 | import android.os.Bundle; |
09 | import android.view.View; |
10 | import android.view.View.OnClickListener; |
11 | import android.widget.Button; |
13 | public class main extends Activity { |
14 | /** Called when the activity is first created. */ |
15 | int notification_id= 19172439 ; |
16 | NotificationManager nm; |
18 | public void onCreate(Bundle savedInstanceState) { |
19 | super .onCreate(savedInstanceState); |
20 | setContentView(R.layout.main); |
21 | nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); |
22 | Button bt1=(Button)findViewById(R.id.bt1); |
23 | bt1.setOnClickListener(bt1lis); |
24 | Button bt2=(Button)findViewById(R.id.bt2); |
25 | bt2.setOnClickListener(bt2lis); |
28 | OnClickListener bt1lis= new OnClickListener(){ |
31 | public void onClick(View v) { |
33 | showNotification(R.drawable.home, "图标边的文字" , "标题" , "内容" ); |
37 | OnClickListener bt2lis= new OnClickListener(){ |
40 | public void onClick(View v) { |
43 | nm.cancel(notification_id); |
47 | public void showNotification( int icon,String tickertext,String title,String content){ |
51 | Notification notification= new Notification(icon,tickertext,System.currentTimeMillis()); |
53 | notification.defaults=Notification.DEFAULT_ALL; |
59 | PendingIntent pt=PendingIntent.getActivity( this , 0 , new Intent( this ,main. class ), 0 ); |
61 | notification.setLatestEventInfo( this ,title,content,pt); |
62 | nm.notify(notification_id, notification); |
AndroidManifest.xml加入权限:
1 | <uses-permission android:name= "android.permission.VIBRATE" /> |