Android API 26 也就是 Version_O 之後有多一個頻道Channel的參數
在設計時要多一個版本的判斷
- 建立NotificationManager
val manager = (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
- 判斷當前手機版本並建立頻道(API 26 以上)
val channelID = "School" val channelName = "Mr.Bob" if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){ val channelSchool = NotificationChannel( channelID, channelName, NotificationManager.IMPORTANCE_DEFAULT ).apply { description = "Description" enableLights(true) enableVibration(true) } manager.createNotificationChannel(channelSchool) }
- 建立 Notification ,這裡使用AndroidX裡面的 NotificationCompat.Builder()
是為了兼容所有版本.
Builder一開始填channel id 也沒關係 .val notification = NotificationCompat.Builder(this,channelID) .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentTitle("<<Tile>>") .setContentText("Text") .setSubText("SubText") .setWhen(System.currentTimeMillis()) .build()
Result
點擊通知後跳轉頁面 Desktop -> MainActivity ,
val intent = Intent(this,MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT) . . . val notification = NotificationCompat.Builder(this,channelID) .setSmallIcon(R.drawable.ic_launcher_foreground) . . //跟上面一樣 . .setContentIntent(pendingIntent) .setWhen(System.currentTimeMillis()) .build()
Result
點擊通知後跳轉頁面 Desktop -> MainActivity -> MainActivity2
新建一個MainActivity2,在AndroidManifest.xml設置,
告訴手機說我要跳到MainActivity2,按返回時會回到MainAcitvity<activity android:name=".MainActivity2" android:exported="true" android:parentActivityName=".MainActivity" />
在設計通知的地方要修改
修改前 val intent = Intent(this,MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
修改後 val intent = Intent(this,MainActivity2::class.java) val stackBuilder = TaskStackBuilder.create(this).apply { addNextIntentWithParentStack(intent) } val pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT)
參考
一開始就學對Android:Kotlin與MVVM新架構
GoogleSearch