不一樣版本通知欄的建立方式不盡相同,當前官方推薦使用 NotificationCompat
相關的API,兼容到Android 4.0,可是部分新功能,好比內嵌回覆操做,舊版本是沒法支持的。java
//CHANNEL_ID,渠道ID,Android 8.0及更高版本必需要設置
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
//設置小圖標
.setSmallIcon(R.drawable.notification_icon)
//設置標題
.setContentTitle(textTitle)
//設置內容
.setContentText(textContent)
//設置等級
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
複製代碼
在 Android 8.0 及更高版本上提供通知,須要在系統中註冊應用的通知渠道。android
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);
}
}
複製代碼
上述代碼應該在應用啓動時當即執行,能夠放在 Application
中進行初始化。markdown
通常點擊通知欄會打開對應的 Activity
界面,具體代碼以下:oop
//點擊時想要打開的界面
Intent intent = new Intent(this, AlertDetails.class);
//通常點擊通知都是打開獨立的界面,爲了不添加到現有的activity棧中,能夠設置下面的啓動方式
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//建立activity類型的pendingIntent,還能夠建立廣播等其餘組件
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)
//設置pendingIntent
.setContentIntent(pendingIntent)
//設置點擊後是否自動消失
.setAutoCancel(true);
複製代碼
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
//notificationId 至關於通知的惟一標識,用於更新或者移除通知
notificationManager.notify(notificationId, builder.build());
複製代碼
還有不少特殊功能,能夠直接查看官網教程進行設置。ui