1. 程式人生 > >Heads Up Notification (setFullScreenIntent not work on Mate8)

Heads Up Notification (setFullScreenIntent not work on Mate8)

本文僅記錄在華為Mate8(Android 7.0)上Heads Up Notification的實現程式碼。至於為什麼這麼實現,由於時間緣故,原因尚未找到。如有同學指點,萬分榮幸!

在Android5.0後,Notification開始支援Heads Up模式。該模式下,不需要下拉通知欄就直接顯示出來 ,懸掛在螢幕上方,並且焦點不變,仍在使用者操作的介面。因此,不會打斷使用者的操作,通知過幾秒就會自動消失。最典型的應用是,微信的聊天訊息通知。網路上對於這種模式的叫法很多,類似橫幅通知,懸掛式通知等。

網上對於實現效果眾說紛紜,大多傾向於呼叫NotificationCompat.Builder的方法

public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority)

但在不同機器上,似乎實現效果也不盡相同。
在華為Mate8(Android 7.0)上,呼叫setFullScreenIntent反而無法實現Heads Up。
最終注掉setFullScreenIntent。核心程式碼如下。

Notification.Builder builder = new Notification.Builder(this);
Intent mIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity
(this, 0, mIntent, 0); builder.setContentIntent(pendingIntent);//設定pendingIntent builder.setSmallIcon(R.drawable.foldleft); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.lanucher)); builder.setAutoCancel(true); builder.setContentTitle("懸掛式通知"); builder.setPriority(Notification.PRIORITY
_MAX);//設定最高許可權 builder.setDefaults(Notification.DEFAULT_ALL);//設定聲音和震動 notificationManager.notify(2, builder.build());

使用Heads Up Notification也有必要前提條件。
(1)Android API >=21,即5.0以上
(2)需要在設定中開啟橫幅通知許可權(在設定通知管理中,不同機型可能存在差異)
(3)需要設定震動或聲音。(必須!)
(4)需要設定Notification為最高許可權。(必須!)

Android對於Notification的設計,個人感覺比較亂。在3.0前後的實現方式不同,且存在很多隱藏的必要條件未說明,可能是需要向前相容的需求吧。

比如,普通的Notification有大小圖示的設定。若不設定大圖示,系統會自動使用APP圖示,但如果不設定小圖示,Notificatin將無法顯示。

需要特別吐槽的是,下面這篇文章。花了我3點CSDN積分下載DEMO,但DEMO中對notification未設定最高許可權等級,未設定聲音/震動,致使Heads Up效果無法展現
《Android5.x Notification應用解析》http://blog.csdn.net/itachi85/article/details/50096609