Android 通知欄的使用方法
一、設(shè)置通知內(nèi)容
//CHANNEL_ID,渠道ID,Android 8.0及更高版本必須要設(shè)置
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
//設(shè)置小圖標(biāo)
.setSmallIcon(R.drawable.notification_icon)
//設(shè)置標(biāo)題
.setContentTitle(textTitle)
//設(shè)置內(nèi)容
.setContentText(textContent)
//設(shè)置等級
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
二、創(chuàng)建渠道
在 Android 8.0 及更高版本上提供通知,需要在系統(tǒng)中注冊應(yīng)用的通知渠道。
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
//不同的重要程度會影響通知顯示的方式
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
上述代碼應(yīng)該在應(yīng)用啟動時立即執(zhí)行,可以放在 Application 中進行初始化。
三、設(shè)置通知欄的點擊操作
一般點擊通知欄會打開對應(yīng)的 Activity 界面,具體代碼如下:
//點擊時想要打開的界面
Intent intent = new Intent(this, AlertDetails.class);
//一般點擊通知都是打開獨立的界面,為了避免添加到現(xiàn)有的activity棧中,可以設(shè)置下面的啟動方式
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//創(chuàng)建activity類型的pendingIntent,還可以創(chuàng)建廣播等其他組件
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
//設(shè)置pendingIntent
.setContentIntent(pendingIntent)
//設(shè)置點擊后是否自動消失
.setAutoCancel(true);
四、顯示通知
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
//notificationId 相當(dāng)于通知的唯一標(biāo)識,用于更新或者移除通知
notificationManager.notify(notificationId, builder.build());
還有很多特殊功能,可以直接查看官網(wǎng)教程進行設(shè)置。
以上就是Android 通知欄的使用方法的詳細內(nèi)容,更多關(guān)于Android 通知欄的使用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Flutter框架實現(xiàn)Android拖動到垃圾桶刪除效果
這篇文章主要介紹了Flutter框架實現(xiàn)Android拖動到垃圾桶刪除效果,Flutter框架中的Draggable部件,用于支持用戶通過手勢拖動,它是基于手勢的一種方式,可以使用戶可以在屏幕上拖動指定的部件,下面我們來詳細了解一下2023-12-12
Android實現(xiàn)藍牙(BlueTooth)設(shè)備檢測連接
這篇文章主要為大家詳細介紹了Android實現(xiàn)藍牙(BlueTooth)設(shè)備檢測連接,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-11-11
Android實現(xiàn)RecyclerView下拉刷新效果
這篇文章主要為大家詳細介紹了Android實現(xiàn)RecyclerView下拉刷新效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
Jetpack?Compose實現(xiàn)對角線滾動效果
這篇文章主要為大家詳細介紹了如何利用Jetpack?Compose實現(xiàn)一個簡單的對角線滾動效果,文中的示例代碼講解詳細,感興趣的小伙伴可以了解一下2023-02-02
flutter BottomAppBar實現(xiàn)不規(guī)則底部導(dǎo)航欄
這篇文章主要為大家詳細介紹了flutter BottomAppBar實現(xiàn)不規(guī)則底部導(dǎo)航欄,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07
Android開發(fā)教程之調(diào)用攝像頭功能的方法詳解
這篇文章主要介紹了Android調(diào)用攝像頭功能的方法,詳細分析了Android調(diào)用攝像頭功能的權(quán)限設(shè)置、功能代碼與實現(xiàn)步驟,需要的朋友可以參考下2016-06-06

