Android 通知欄的使用方法
//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 中進(jìn)行初始化。
三、設(shè)置通知欄的點(diǎn)擊操作一般點(diǎn)擊通知欄會打開對應(yīng)的 Activity 界面,具體代碼如下:
//點(diǎn)擊時想要打開的界面 Intent intent = new Intent(this, AlertDetails.class); //一般點(diǎn)擊通知都是打開獨(dú)立的界面,為了避免添加到現(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è)置點(diǎn)擊后是否自動消失 .setAutoCancel(true); 四、顯示通知
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); //notificationId 相當(dāng)于通知的唯一標(biāo)識,用于更新或者移除通知 notificationManager.notify(notificationId, builder.build());
還有很多特殊功能,可以直接查看官網(wǎng)教程進(jìn)行設(shè)置。
以上就是Android 通知欄的使用方法的詳細(xì)內(nèi)容,更多關(guān)于Android 通知欄的使用的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 詳解Android studio 動態(tài)fragment的用法2. 解決Android studio xml界面無法預(yù)覽問題3. 圖文詳解vue中proto文件的函數(shù)調(diào)用4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)5. php模擬實(shí)現(xiàn)斗地主發(fā)牌6. 什么是python的自省7. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. vue 使用localstorage實(shí)現(xiàn)面包屑的操作9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備