Notification 使用詳解

2021-02-14 程式設計師Android

和你一起終身學習,這裡是程式設計師Android

經典好文推薦,通過閱讀本文,您將收穫以下知識點:

一、Notification 簡介
二、創建Notification 的方法
三、通知的管理
四、簡單的通知實現
五、可擴展通知實現
六、通知中含下載進度條
七、通知中含媒體播放控制項
八、自定義通知內容

一、Notification 簡介

Notification 通知是應用向用戶顯示的消息提示,當發送通知時,通知將先以圖標的形式顯示在通知區域中。用戶可以打開下拉通知欄查看通知的詳細信息。通知區域和下拉通知欄均是由系統控制的區域,用戶可以隨時查看。

通知在Android用戶界面的一個重要部分,其使用方法請看以下內容:

通知區域中的通知

下拉通知欄中的通知

二、創建Notification 的方法

調用NotificationCompat.Builder.build() 創建Notification對象,然後調用 NotificationManager.notify() 將Notification對象傳遞給系統。

通知默認優先級為 PRIORITY_DEFAULT 0
Notification.Builder.setPriority()
5個級別可選(-2、-1、0、1、2)

通知優先級如下:

PRIORITY_LOW=-1
PRIORITY_MIN=-2
PRIORITY_DEFAULT = 0
PRIORITY_HIGH=1
PRIORITY_MAX=2

通過Notification.Builder.setStyle()可以設置通知的樣式。

通知中經常遇到,點擊通知欄,打開 Activity。



Notification.Builder mBuilder = new Notification.Builder(this);

mBuilder.setSmallIcon(R.drawable.gril)
.setDefaults(Notification.DEFAULT_SOUND).setColor(000)
.setContentTitle("簡單通知Tittle").setContentText("點擊可以打開Activity");

Intent resultIntent = new Intent(this, NotificationMethods.class);
// 新開一個Activity 棧

resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationMethods.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());

三、通知的管理

調用 NotificationManager.notify(ID) 發出帶有通知ID的通知,ID相同,即可更新以前ID發送的通知。

創建時 調用了 setAutoCancel(true)
刪除時候調用刪除指定ID

NotificationManager.cancel(notificationId)

刪除自己應用發的所有通知

Utils.mNotificationManager.cancelAll();

setProgress()

四、簡單的通知實現

簡單通知圖片

/**
* 簡單通知
*/
public void SimpleNotification(View view) {

Notification.Builder mBuilder = new Notification.Builder(this);

mBuilder.setSmallIcon(R.drawable.gril)
.setDefaults(Notification.DEFAULT_SOUND).setColor(000)
.setContentTitle("簡單通知Tittle").setContentText("點擊可以打開Activity");

Intent resultIntent = new Intent(this, NotificationMethods.class);
// 新開一個Activity 棧

resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationMethods.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}

五、可擴展通知實現

通知展開圖

通知未展開圖


/**
* 可擴展通知
* **/
public void NotificationStyle(View view) {

Notification.Builder mBuilder = new Notification.Builder(this);

mBuilder.setLargeIcon(
DrawableUtils.DrawableToBitmap(getResources().getDrawable(
R.drawable.ic_launcher)))
.setContentTitle("我是可擴展通知的Tittle ")
.setDefaults(Notification.DEFAULT_SOUND)

.setContentText("我是可擴展通知的內容")
.setSmallIcon(R.drawable.ic_launcher)
.setAutoCancel(true)
.setStyle(
new Notification.InboxStyle().addLine("我是可擴展通知第一行")
.addLine("我是可擴展通知第二行")
.setBigContentTitle("我是可擴展的大 Tittle")
.setSummaryText("點擊,展開獲取更多內容"));

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 如果Id 一樣可以更新通知
mNotificationManager.notify(1, mBuilder.build());
}

六、通知中含下載進度條

下載中通知

下載完成通知


/**
* 帶有下載進度條的通知
* **/
public void NotificationProcess(View view) {

final NotificationManager mNotifyManagerProcess;
final Notification.Builder mBuilder;
mNotifyManagerProcess = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new Notification.Builder(this);
mBuilder.setContentTitle("Picture Downloading").setSmallIcon(
R.drawable.ic_launcher);
new Thread(new Runnable() {
@Override
public void run() {
for (MIncr = 0; MIncr <= 100; MIncr += 1 + 5 * Math.random()) {
mBuilder.setProgress(100, MIncr, false).setContentText(
MIncr + "%");
mNotifyManagerProcess.notify(2, mBuilder.build());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
/**
* setProgress true 則表示 進度條一直不停的從左至右滑動,類似於圓形進度條 false :進度條消失
* **/
mBuilder.setContentText("Download complete").setProgress(0, 0,
false);
mNotifyManagerProcess.notify(2, mBuilder.build());
}
}).start();
}

七、通知中含媒體播放控制項

未展開圖

展開圖

/**
* 音樂播放器樣式
* **/
public void NotificationMediaStyle(View view) {
Notification.Builder mMediaBuilder = new Notification.Builder(this);
mMediaBuilder.setSmallIcon(R.drawable.ic_launcher);
mMediaBuilder.setContentTitle("如果有一天我變有錢");
mMediaBuilder.setContentText("毛不易");
mMediaBuilder.setLargeIcon(DrawableUtils
.DrawableToBitmap(getResources().getDrawable(
R.drawable.ic_launcher)));
Intent mIntent = new Intent();
ComponentName name = new ComponentName(this, NotificationMethods.class);
mIntent.setComponent(name);
PendingIntent mPendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, mIntent, 0);
mMediaBuilder.setContentIntent(mPendingIntent);
mMediaBuilder.setPriority(Notification.PRIORITY_MAX);
mMediaBuilder.addAction(new Notification.Action.Builder(Icon
.createWithResource(NotificationMethods.this,
R.drawable.music_pre), "1", null).build());
mMediaBuilder.addAction(new Notification.Action.Builder(Icon
.createWithResource(NotificationMethods.this,
R.drawable.music_play), "2", null).build());
mMediaBuilder.addAction(new Notification.Action.Builder(Icon
.createWithResource(NotificationMethods.this,
R.drawable.music_next), "3", null).build());

Notification.MediaStyle mMediaStyle = new Notification.MediaStyle();
mMediaStyle.setShowActionsInCompactView(0, 1, 2);
mMediaBuilder.setStyle(mMediaStyle);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// 如果Id 一樣可以更新通知
mNotificationManager.notify(1, mMediaBuilder.build());
}

八、自定義通知內容

自定義通知效果圖

/**
* 自定義樣式通知
* **/
public void NotificationCustomView(View view) {

/***
* 自定義Remoteview
* **/
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.notification_view);
remoteViews.setTextViewText(R.id.tv_content_title, "十年");
remoteViews.setTextViewText(R.id.tv_content_text, "陳奕迅");
// 打開上一首
remoteViews.setOnClickPendingIntent(R.id.btn_pre,
SetClickPendingIntent(NOTIFICATION_PRE));
// 打開下一首
remoteViews.setOnClickPendingIntent(R.id.btn_next,
SetClickPendingIntent(NOTIFICATION_NEXT));
// 點擊整體布局時,打開播放器
remoteViews.setOnClickPendingIntent(R.id.btn_play,
SetClickPendingIntent(NOTIFICATION_PLAY));
// 點擊整體布局時,打開Activity
remoteViews.setOnClickPendingIntent(R.id.ll_root,
SetClickPendingIntent(NOTIFICATION_ACTIVITY));

remoteViews.setOnClickPendingIntent(R.id.img_clear,
SetClickPendingIntent(NOTIFICATION_CANCEL));

Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("當前正在播放..")
.setWhen(System.currentTimeMillis())
.setContentTitle("十年")
.setContentText("陳奕迅")
.setAutoCancel(true)
.setLargeIcon(
DrawableUtils.DrawableToBitmap(getResources()
.getDrawable(R.drawable.ic_launcher)))
.setContent(remoteViews);

Utils.mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 打開通知
Utils.mNotificationManager.notify(Utils.NOTIFICATION_CUSTOM_ID,
builder.build());
}

public PendingIntent SetClickPendingIntent(int what) {
switch (what) {

case NOTIFICATION_PRE:
Intent intentPre = new Intent(this, MainActivity.class);
intentPre.putExtra("cmd", what);
int flagPre = PendingIntent.FLAG_UPDATE_CURRENT;
PendingIntent clickPreIntent = PendingIntent.getActivity(this,
what, intentPre, flagPre);
return clickPreIntent;

case NOTIFICATION_PLAY:
Intent intentPlay = new Intent(this, NotificationMethods.class);
intentPlay.putExtra("cmd", what);
int flagPlay = PendingIntent.FLAG_UPDATE_CURRENT;
PendingIntent clickPlayIntent = PendingIntent.getActivity(this,
what, intentPlay, flagPlay);
return clickPlayIntent;
case NOTIFICATION_NEXT:
Intent intentNext = new Intent(this, ActivityMethods.class);
intentNext.putExtra("cmd", what);
int flagNext = PendingIntent.FLAG_UPDATE_CURRENT;
PendingIntent clickNextIntent = PendingIntent.getActivity(this,
what, intentNext, flagNext);
return clickNextIntent;
case NOTIFICATION_ACTIVITY:
Intent intentActivity = new Intent(this, ServiceMethod.class);
intentActivity.putExtra("cmd", what);
int flag = PendingIntent.FLAG_UPDATE_CURRENT;
PendingIntent clickIntent = PendingIntent.getActivity(this, what,
intentActivity, flag);
Toast.makeText(getApplicationContext(), "打開Activity", 0).show();
return clickIntent;
case NOTIFICATION_CANCEL:

Intent intentCancel = new Intent("Notification_cancel");
intentCancel.putExtra("cancel_notification_id",
Utils.NOTIFICATION_CUSTOM_ID);
int flagCancel = PendingIntent.FLAG_CANCEL_CURRENT;
PendingIntent clickCancelIntent = PendingIntent.getBroadcast(this,
0, intentCancel, flagCancel);
return clickCancelIntent;
default:
break;
}
return null;

}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#282828"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="8dp" >

<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="5dp"
android:src="@drawable/ic_launcher" />

<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:orientation="vertical" >

<TextView
android:id="@+id/tv_content_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="18sp"
android:text="十年"
android:textColor="@android:color/white" />

<TextView
android:id="@+id/tv_content_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:text="陳奕迅"
android:textSize="14sp"
android:textColor="@android:color/white" />
</LinearLayout>

<Button
android:id="@+id/btn_pre"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="@drawable/music_pre" />

<Button
android:id="@+id/btn_play"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="8dp"
android:background="@drawable/music_play" />

<Button
android:id="@+id/btn_next"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="8dp"
android:background="@drawable/music_next" />

<ImageView
android:id="@+id/img_clear"
android:layout_width="30dp"
android:layout_height="match_parent"
android:layout_gravity="top|center_horizontal"
android:padding="6dp"
android:src="@drawable/clear_img" />

</LinearLayout>

case NOTIFICATION_CANCEL:

Intent intentCancel = new Intent("Notification_cancel");
intentCancel.putExtra("cancel_notification_id",
Utils.NOTIFICATION_CUSTOM_ID);
int flagCancel = PendingIntent.FLAG_CANCEL_CURRENT;
PendingIntent clickCancelIntent = PendingIntent.getBroadcast(this,
0, intentCancel, flagCancel);
return clickCancelIntent;

註冊方式如下:

<receiver
android:name="com.programandroid.BroadcastReceiver.NotificationReceived"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="Notification_cancel" />
<action android:name="Notification_music_pre" />
<action android:name="Notification_music_play" />
<action android:name="Notification_music_next" />
</intent-filter>
</receiver>

至此,本篇已結束。轉載網絡的文章,小編覺得很優秀,歡迎點擊閱讀原文,支持原創作者,如有侵權,懇請聯繫小編刪除。同時感謝您的閱讀,期待您的關注。

點個在看,方便您使用時快速查找!

相關焦點

  • SIP Push Notification功能有救了?
    基於移動端軟電話APP已經在很多場景中使用,用戶通過手機app 實現企業電話系統的呼叫或者其他功能。但是,在軟電話使用環境中,很多時候因為系統推送的問題,呼叫進入到終端時,app 根本沒有被喚醒,或者在線狀態丟失,因此就會漏接很多通話。此業務功能一直因為喚醒處理流程存在的問題,導致用戶體驗相對比較差。
  • Pokemon Go定位器使用教學 定位器pokevision使用詳解
    Pokemon Go定位器使用教學,定位器pokevision使用詳解。今天小編給大家帶來的是Pokemon Go定位器使用教學,定位器pokevision使用詳解,下面一起來看看。
  • 2018考研英語大綱熟詞僻義詳解(8)
    下面新東方網考研頻道分享考研英語大綱熟詞僻義詳解,大家注意把握。 2018考研英語大綱熟詞僻義詳解(8)   Import(4次)   【熟義熟性】 v.進口,輸入;n.進口,輸入Import and export 進出口   【真題例句】 The OECD estimates in its latest Economic
  • 《陰陽師》最新金御札怎麼使用 金御札使用詳解
    導 讀 陰陽師金御札怎麼使用?
  • PS中濾鏡如何使用?PS濾鏡的使用方法詳解
    PS中濾鏡如何使用?PS濾鏡的使用方法詳解!ps中的濾鏡非常強大,往往可以做出我們意想不到的好看畫面,想要熟練的運用這個工具,這就需要大家在平時自己多多實踐,有事沒事就練練。這裡微課菌就做個簡單的例子來讓你體會一下濾鏡的強悍。
  • 微波爐使用方法詳解
    【導讀】微波爐是利用微波輻射進行加熱的,食物中一般都含有一定的水分,而水是由極性分子所組成的,這種極性分子會隨著微波磁場的變動而變化。食物中極性分子會和相鄰分子之間相互產生作用,使水溫不斷的升高,食物的溫度也隨之升高。微波爐使用時要安放在平整、通風的臺面或擱架上。
  • 《明日之後》攀爬繩索怎麼使用 攀爬繩索使用方法詳解
    不過很多新手玩家還不太了解明日之後攀爬繩索怎麼用,下面小編就為大家帶來明日之後攀爬繩索使用方法詳解,一起來看看吧。 攀爬繩索可以在破損的屋頂下使用,因此玩家要想通過繩索從一樓爬到二樓的話,需要先將二樓的地板擊破,接著只要將繩索往上面扔,就能形成一個繩子讓玩家爬上去了。
  • 《方舟生存進化》寵物玩具如何使用 寵物玩具使用詳解
    導 讀 這是一篇關於方舟生存進化寵物玩具怎麼用,寵物玩具類型與用法詳解的文章。
  • Vue開發使用Axios遇到了大坑!
    我使用angular的http請求,區域網內連接開發工程,一切正常!使用Vue的axios連接部分正常,部分不正常,伺服器狀態碼200,伺服器端控制臺也不報錯。但是頁面請求就是報錯。使用iPhone手機報錯,換華為安卓手機也是一樣的報錯,安卓手機不知道怎麼調試,使用macOS的Safari瀏覽器可以調試iPhone手機瀏覽器,調試報錯,但是不知道原因。
  • 畫中畫使用方法教程圖文詳解
    畫中畫使用方法教程圖文詳解時間:2020-11-24 23:41   來源:今日頭條   責任編輯:毛青青 川北在線核心提示:原標題:剪映畫中畫視頻怎麼弄?畫中畫使用方法教程圖文詳解 剪映畫中畫視頻怎麼製作?剪映視頻製作軟體的功能還是很強大的,現在小編給大家說下畫中畫使用方法教程圖文詳解,希望可以幫到大家。
  • 第一課 MetaSploit-Framework介紹與使用詳解
    MetaSploit-Framework從理論到實戰山丘安全攻防實驗室第一課 MetaSploit-Framework介紹與使用詳解MetaSploit-Framework簡介Metasploit是一款開源的滲透測試框架平臺,到目前為止,msf已經內置了數千個 已披露的漏洞相關的模塊和滲透測試工具,模塊使用ruby語言編寫,這使得使用者 能夠根據需要對模塊進行適當修改,甚至是調用自己寫的測試模塊。
  • 使命召喚手遊閃光彈怎麼用 閃光彈使用方法詳解
    今天小編就為大家介紹下閃光彈使用方法詳解,我們一起來看看吧! 使命召喚手遊閃光彈使用方法詳解: 閃光彈可以幹擾敵人的視覺和聽覺,但是動作不受太大影響,同時也可以幹擾敵人的絆雷、哨戒機槍和防空飛彈,在攻堅戰時是必不可少的戰術裝備。
  • 輻射4自帶效果的注射器步槍使用優缺點詳解
    導 讀 輻射4自帶效果的注射器步槍使用優缺點詳解,注射器步槍是遊戲中獨特的武器之一,沒什麼傷害但有各種效果可以運用在戰術上
  • Java枚舉使用詳解
    在java中如何更好的使用這些「數據集」呢?因此枚舉便派上了用場,以下代碼詳細介紹了枚舉的用法。package com.ljq.test; /** * 枚舉用法詳解 * * @author jiqinlin * */ public class TestEnum { /** * 普通枚舉 * * @author jiqinlin * */ public enum ColorEnum { red, green, yellow, blue; } /** * 枚舉像普通的類一樣可以添加屬性和方法
  • MySQL 中DROP USER語句的使用詳解
    但是在使用drop user語句之前,應該撤銷用戶的特權,或者換句話說,如果用戶沒有特權,那麼可以使用drop user語句從Mysql資料庫伺服器刪除用戶。語法:DROP USER 'user'@'host';參數:1. user:這是要刪除的用戶帳戶的用戶名。2. host:它是用戶帳戶的主機伺服器名。
  • SSD死機卡頓怎麼辦 固態硬碟使用詳解
    SSD死機卡頓怎麼辦 固態硬碟使用詳解    我們先一起來看看死機問題主要集中在那幾個方面,何為正常死機,什麼又是非正常死機:假象死機>    1:程序卡死導致的畫面定格,甚至滑鼠指針都無法看到,但WIN7可使用Ctrl+Alt+Del切換至登錄/註銷界面強制註銷或重啟;    2:任意原因導致的電腦無任何響應,滑鼠鍵盤鎖死無法操作,一段時間後電腦藍屏,自動重啟或需用戶手動重啟;    3:系統繁忙導致的短時間內無法響應用戶操作,一段時間後恢復;    4:畫面基本定格,但滑鼠鍵盤無鎖死
  • 直播貼紙功能設置和使用方法圖文詳解
    直播貼紙功能設置和使用方法圖文詳解時間:2020-11-18 23:43   來源:今日頭條   責任編輯:毛青青 川北在線核心提示:原標題:快手直播貼紙怎麼設置?直播貼紙功能設置和使用方法圖文詳解 快手直播貼紙怎麼弄?很多用戶還不會設置,現在小編給大家說下直播貼紙功能設置和使用方法圖文詳解。
  • 西門子s7-300功能使用詳解
    1)S7-300硬體詳解(第1,2課時)2)單站的硬體組態(第3,4課時)3)單機架擴展組態(第5,6課時)4)多機架擴展組態(第7,8課時)5)主站和遠程I/O組態(第9,10課時)6)主站CPU與從站CPU通訊組態(第11,12課時)7)主站CPU與主站CPU通訊組態(第13,14課時)8)S7-300與S7-200通訊組態
  • 星界邊境秘籍大全 控制臺指令匯總使用方法詳解
    《星界邊境》指令怎麼使用?遊戲中使用控制臺的話可省去不少精力,今天小編帶來「justin5566」分享的《星界邊境》控制臺指令使用方法詳解,一起來看吧。以上就是《星界邊境》控制臺指令使用方法詳解,希望對各位有所幫助。
  • 《絕地求生》信號槍怎麼用使用教程詳解
    只有一發的信號彈要如何使用?信號槍信號彈好不好用、這個東東到底值不值得去搶呢?一起來了解下吧。 更讓人震驚的是,這還是個雙黃蛋,... 絕地求生信號槍這個東東可以說是相當有趣了,信號槍有什麼用?只有一發的信號彈要如何使用?信號槍信號彈好不好用、這個東東到底值不值得去搶呢?一起來了解下吧。