Android安卓狀態列訊息推送通知(Notification)
阿新 • • 發佈:2018-11-12
我從不猜測,猜測是一個很壞的習慣——會影響正常的邏輯推理能力。 ——阿瑟·柯南·道爾 《福爾摩斯探案集》
近日,在做安卓專案開發的時候涉及到狀態列通知的需求,查了資料,總結一個簡單有效的方法,下面放上程式碼(Kotlin版):
//該程式碼為Kotlin,讀者可根據需求稍作調整 val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager var notification: Notification val intent = PendingIntent.getActivity(this, 100, Intent(this, MainActivity::class.java), PendingIntent.FLAG_CANCEL_CURRENT) val largeIcon = BitmapFactory.decodeResource( this.resources, android.R.drawable.ic_media_play) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ val mChannel = NotificationChannel("id", "name",NotificationManager.IMPORTANCE_LOW) notificationManager.createNotificationChannel(mChannel) notification = Notification.Builder(this) .setChannelId("id") .setContentTitle("標題") .setContentText("內容內容內容內容內容內容內容內容內容內容") .setContentIntent(intent) .setLargeIcon(largeIcon) .setSmallIcon(android.R.drawable.ic_media_play).build() }else{ val builder = NotificationCompat.Builder(this) .setContentTitle("標題") .setContentText("內容內容內容內容內容內容內容內容內容內容") .setDefaults(NotificationCompat.DEFAULT_ALL) .setAutoCancel(true) .setLargeIcon(largeIcon) .setSmallIcon(android.R.drawable.ic_media_play) .setContentIntent(intent) notification = builder.build() } notificationManager.notify(0,notification)