android notification 總結


notification是一種出現在任務欄的提示,特別是在4.0以后notification改進了不少,本文內容都是基於4.0及4.1以后總結來的。

分類


 notification有以下幾種:

  1>普通notification

  

    1.內容標題

    2.大圖標

    3.內容

    4.內容附加信息

    5.小圖標

    6.時間

  2>大布局Notification

    圖1

  大布局notification是在android4.1以后才增加的,大布局notification與小布局notification只在‘7’部分有區別,其它部分都一致。大布局notification只有在所有notification的最上  面時才會顯示大布局,其它情況下顯示小布局。你也可以用手指將其擴展為大布局(前提是它是大布局)。如下圖:

  圖2

    大布局notification有三種類型:如圖1為NotificationCompat.InboxStyle 類型。圖2左部為NotificationCompat.BigTextStyle。圖2右部      為:NotificationCompat.BigPictureStyle

   3>自定義布局notification

     除了系統提供的notification,我們也可以自定義notification。如下圖所示的一個音樂播放器控制notification:

    圖3

如何創建notification


 

    1>實例化一個NotificationCompat.Builder對象;如builder

     2>調用builder的相關方法對notification進行上面提到的各種設置

    3>調用builder.build()方法此方法返回一個notification對象。

     4>實例化一個NotificationManager對象;如:manager

     5>調用manager的notify方法。

  注:

   一個notification不必對上面所有的選項都進行設置,但有3項是必須的:

   小圖標, set by setSmallIcon()

     內容標題, set by setContentTitle()

     內容, set by setContentText()

示例代碼


示例程序截圖:

 

0>初始化部分代碼

View Code
 1 public class MainActivity extends Activity implements OnClickListener {
 2 
 3     private static final int NOTIFICATION_ID_1 = 0;
 4     private static final int NOTIFICATION_ID_2 = 1;
 5     private static final int NOTIFICATION_ID_3 = 2;
 6     private static final int NOTIFICATION_ID_4 = 3;
 7     private static final int NOTIFICATION_ID_5 = 4;
 8     private static final int NOTIFICATION_ID_6 = 5;
 9     private static final int NOTIFICATION_ID_7 = 6;
10     private static final int NOTIFICATION_ID_8 = 7;
11 
12     private static int messageNum = 0;
13     private Context context = this;
14     private NotificationManager manager;
15     private Bitmap icon;
16     private static final int[] btns = new int[] { R.id.btn1, R.id.btn2,
17             R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8,
18             R.id.btn9 };
19 
20     @Override
21     protected void onCreate(Bundle savedInstanceState) {
22         super.onCreate(savedInstanceState);
23         setContentView(R.layout.activity_main);
24         init();
25     }
26 
27     private void init() {
28         // 獲取通知服務
29         manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
30         // 注冊監聽器
31         for (int btn : btns) {
32             findViewById(btn).setOnClickListener(this);
33         }
34 
35         icon = BitmapFactory.decodeResource(getResources(),
36                 R.drawable.ic_launcher);
37     }
38 
39     @Override
40     public void onClick(View v) {
41         switch (v.getId()) {
42         case R.id.btn1:
43             showNormal();
44             break;
45         case R.id.btn2:
46             showBigView_Text();
47             break;
48         case R.id.btn3:
49             showBigView_Pic();
50             break;
51         case R.id.btn4:
52             showBigView_Inbox();
53             break;
54         case R.id.btn5:
55             showCustomView();
56             break;
57         case R.id.btn6:
58             backApp();
59             break;
60         case R.id.btn7:
61             backScreen();
62             break;
63         case R.id.btn8:
64             showProgressBar();
65             break;
66         case R.id.btn9:
67             dismiss();
68             break;
69         default:
70             Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
71             break;
72         }
73     }
74 
75     private void dismiss() {
76         manager.cancelAll();
77     }

 

1>普通notification

View Code
 1     private void showNormal() {
 2 
 3         Notification notification = new NotificationCompat.Builder(context)
 4                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
 5                 .setTicker("showNormal").setContentInfo("contentInfo")
 6                 .setContentTitle("ContentTitle").setContentText("ContentText")
 7                 .setNumber(++messageNum)
 8                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
 9                 .build();
10         manager.notify(NOTIFICATION_ID_1, notification);
11     }

 

2>大布局Text類型notification

View Code
 1 private void showBigView_Text() {
 2         NotificationCompat.BigTextStyle textStyle = new BigTextStyle();
 3         textStyle
 4                 .setBigContentTitle("BigContentTitle")
 5                 .setSummaryText("SummaryText")
 6                 .bigText(
 7                         "I am Big Texttttttttttttttttttttttttttttttttttttttttttt!!!!!!!!!!!!!!!!!!!......");
 8         Notification notification = new NotificationCompat.Builder(context)
 9                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
10                 .setTicker("showBigView_Text").setContentInfo("contentInfo")
11                 .setContentTitle("ContentTitle").setContentText("ContentText")
12                 .setStyle(textStyle)
13                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
14                 .build();
15         manager.notify(NOTIFICATION_ID_2, notification);
16     }

 

3> 大布局Picture類型notificatio

View Code
 1 private void showBigView_Pic() {
 2         NotificationCompat.BigPictureStyle pictureStyle = new BigPictureStyle();
 3         pictureStyle.setBigContentTitle("BigContentTitle")
 4                 .setSummaryText("SummaryText").bigPicture(icon);
 5         Notification notification = new NotificationCompat.Builder(context)
 6                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
 7                 .setTicker("showBigView_Pic").setContentInfo("contentInfo")
 8                 .setContentTitle("ContentTitle").setContentText("ContentText")
 9                 .setStyle(pictureStyle)
10                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
11                 .build();
12         manager.notify(NOTIFICATION_ID_3, notification);
13     }

 

4>大布局Inbox類型notification

View Code
 1 private void showBigView_Inbox() {
 2         NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
 3         inboxStyle.setBigContentTitle("BigContentTitle").setSummaryText(
 4                 "SummaryText");
 5         for (int i = 0; i < 5; i++)
 6             inboxStyle.addLine("news:" + i);
 7         Notification notification = new NotificationCompat.Builder(context)
 8                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
 9                 .setTicker("showBigView_Inbox").setContentInfo("contentInfo")
10                 .setContentTitle("ContentTitle").setContentText("ContentText")
11                 .setStyle(inboxStyle)
12                 .setAutoCancel(true).setDefaults(Notification.DEFAULT_ALL)
13                 .build();
14         manager.notify(NOTIFICATION_ID_4, notification);
15     }

 

5>自定義notification

效果圖:

並對中間的播放按鈕做了一個簡單的點擊處理事件(點擊播放后,請關閉幕簾否則可能會看不到toast提示)

View Code
 1 private void showCustomView() {
 2         RemoteViews remoteViews = new RemoteViews(getPackageName(),
 3                 R.layout.custom_notification);
 4         Intent intent = new Intent(this, TestMusicControl.class);
 5         PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
 6                 intent, 0);
 7         remoteViews.setOnClickPendingIntent(R.id.paly_pause_music,
 8                 pendingIntent);
 9         NotificationCompat.Builder builder = new Builder(context);
10         builder.setContent(remoteViews).setSmallIcon(R.drawable.music_icon)
11                 .setLargeIcon(icon).setOngoing(true)
12                 .setTicker("music is playing");
13         manager.notify(NOTIFICATION_ID_8, builder.build());
14     }

 布局文件:

View Code
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:gravity="center_vertical"
 6     android:orientation="horizontal" >
 7 
 8     <ImageView
 9         android:id="@+id/songer_pic"
10         android:layout_width="64dp"
11         android:layout_height="64dp"
12         android:src="@drawable/yan" />
13 
14     <LinearLayout
15         android:layout_width="fill_parent"
16         android:layout_height="fill_parent"
17         android:gravity="center_vertical"
18         android:orientation="horizontal" >
19 
20         <ImageView
21             android:id="@+id/last_music"
22             android:layout_width="0dp"
23             android:layout_height="48dp"
24             android:layout_weight="1"
25             android:src="@drawable/music_previous" />
26 
27         <ImageView
28             android:id="@+id/paly_pause_music"
29             android:layout_width="0dp"
30             android:layout_height="48dp"
31             android:layout_weight="1"
32             android:src="@drawable/music_play" />
33 
34         <ImageView
35             android:id="@+id/next_music"
36             android:layout_width="0dp"
37             android:layout_height="48dp"
38             android:layout_weight="1"
39             android:src="@drawable/music_next" />
40     </LinearLayout>
41 
42 </LinearLayout>

 

帶進度條的notification

View Code
 1     private void showProgressBar() {
 2 
 3         final NotificationCompat.Builder builder = new NotificationCompat.Builder(
 4                 context);
 5         builder.setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
 6                 .setTicker("showProgressBar").setContentInfo("contentInfo")
 7                 .setOngoing(true).setContentTitle("ContentTitle")
 8                 .setContentText("ContentText");
 9         new Thread(new Runnable() {
10 
11             @Override
12             public void run() {
13 
14                 int progress = 0;
15 
16                 for (progress = 0; progress < 100; progress += 5) {
17                     //將setProgress的第三個參數設為true即可顯示為無明確進度的進度條樣式
18                     builder.setProgress(100, progress, false);
19                     manager.notify(NOTIFICATION_ID_7, builder.build());
20                     try {
21                         // Sleep for 5 seconds
22                         Thread.sleep(2 * 1000);
23                     } catch (InterruptedException e) {
24                         System.out.println("sleep failure");
25                     }
26                 }
27                 builder.setContentTitle("Download complete")
28                         .setProgress(0, 0, false).setOngoing(false);
29                 manager.notify(NOTIFICATION_ID_7, builder.build());
30 
31             }
32         }).start();
33     }

  

點擊事件處理 


  有時候我們可能需要實現這樣的功能:當新notification出現時,我們希望點擊它后可直接進入應用相應的界面中去完整查看或處理此消息的功能。然后,當我們點擊back按鈕時返回到應用主界面而不是桌面。比如:當我們有新的短信來時,我們在任務欄中點擊它后進入讀信息頁面,當我們讀完短信后,按“返回”鍵回到短信的主界面,而不是手機桌面。要實現這樣的功能要我們做相應的處理:

1>返回應用主界面

View Code
 1     private void backApp() {
 2 
 3         TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
 4         // Adds the back stack
 5         stackBuilder.addParentStack(OtherActivity.class);
 6         // Adds the Intent to the top of the stack
 7         Intent resultIntent = new Intent(this, OtherActivity.class);
 8         stackBuilder.addNextIntent(resultIntent);
 9         // Gets a PendingIntent containing the entire back stack
10         PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
11                 PendingIntent.FLAG_UPDATE_CURRENT);
12 
13         Notification notification = new NotificationCompat.Builder(context)
14                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
15                 .setTicker("backApp").setContentInfo("contentInfo")
16                 .setContentTitle("ContentTitle").setContentText("ContentText")
17                 .setContentIntent(resultPendingIntent).setAutoCancel(true)
18                 .setDefaults(Notification.DEFAULT_ALL).build();
19         manager.notify(NOTIFICATION_ID_5, notification);
20         this.finish();
21     }

 

並需要我們在配置文件中對我們用來顯示詳細信息的OtherActivity進行相應的配置如下:

1   <activity
2             android:name="com.example.notification.OtherActivity"
3             android:label="@string/title_activity_other"
4             android:parentActivityName=".MainActivity" >
5             <meta-data
6                 android:name="android.support.PARENT_ACTIVITY"
7                 android:value=".MainActivity" />
8         </activity>

 2>直接返回桌面

   有些時候我們可能需要實現這樣的功能:當我們點擊notification時彈出一個稍大點的窗口來顯示整個消息,這窗口的作用就是用來顯示整個消息內容的,和此應用內的其它Activity都沒有關系,然后當我們點擊"back"后直接返回到手機桌面。要實現這樣的功能我們只需要調用builder的.setContentIntent方法,然后對所要跳轉到的activity在配置文件中進行一些配置:

View Code
 1 private void backScreen() {
 2         Intent notifyIntent = new Intent(this, SpecialActivity.class);
 3         // Sets the Activity to start in a new, empty task
 4         notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
 5                 | Intent.FLAG_ACTIVITY_CLEAR_TASK);
 6         // Creates the PendingIntent
 7         PendingIntent notify_Intent = PendingIntent.getActivity(this, 0,
 8                 notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
 9 
10         Notification notification = new NotificationCompat.Builder(context)
11                 .setLargeIcon(icon).setSmallIcon(R.drawable.ic_launcher)
12                 .setTicker("backScreen").setContentInfo("contentInfo")
13                 .setContentTitle("ContentTitle").setContentText("ContentText")
14                 .setContentIntent(notify_Intent).setAutoCancel(true)
15                 .setDefaults(Notification.DEFAULT_ALL).build();
16         manager.notify(NOTIFICATION_ID_6, notification);
17         this.finish();
18     }

 配置文件:

View Code
1  <activity
2             android:name="com.example.notification.SpecialActivity"
3             android:excludeFromRecents="true"
4             android:label="@string/title_activity_special"
5             android:launchMode="singleTask"
6             android:taskAffinity="" >

源碼下載

更詳細內容請參考:http://developer.android.com/guide/topics/ui/notifiers/notifications.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM