我正在嘗試在我的 android 應用程式中實作通知。當用戶點擊通知時,如果活動尚未運行,我會運行該活動..但如果活動已經在運行,我不想重新創建它,我只想通過攔截來自 onNewIntent 的意圖來重繪 資料功能。問題是每次單擊通知時,都會重新創建活動,并且不會呼叫 onNewIntent 函式。
當我從服務創建通知時會出現問題。但是當我從要運行的同一活動創建通知時,一切正常。
我在互聯網上搜索并嘗試了我找到的所有解決方案,但它仍然不起作用
我嘗試了幾種意圖示志的組合,但沒有任何效果
這是我的代碼
val intent : Intent = Intent(this, HomeActivity::class.java)
finalIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
val pendingIntentFlags : Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
{
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
}
else
{
PendingIntent.FLAG_UPDATE_CURRENT
}
val pendingIntent : PendingIntent? = TaskStackBuilder.create(context).run {
addNextIntentWithParentStack(finalIntent)
getPendingIntent(0, pendingIntentFlags)
}
val notification = NotificationCompat.Builder(context, type.channelId)
.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(Notification.CATEGORY_SERVICE)
.setDefaults(Notification.DEFAULT_ALL)
.setAllowSystemGeneratedContextualActions(true)
.setOnlyAlertOnce(true)
.setAutoCancel(true)
.setLocalOnly(true)
.setOngoing(false)
.setSilent(false)
.setSmallIcon(R.drawable.icon_notification)
.setContentIntent(pendingIntent)
.build()
notificationManager?.notify(NOTIFICATION_ID, notification)
uj5u.com熱心網友回復:
讓您的通知發送廣播。在您的活動中,您應該注冊一個動態廣播接收器。這將允許您重繪 活動中的內容而無需重新加載它。
對于活動未運行的情況,您應該在清單中定義一個廣播接收器來啟動活動。當您的活動開始時,禁用廣播接收器并在您的活動停止時重新啟用它。
uj5u.com熱心網友回復:
您可以singleInstance在您的活動的清單中將啟動模式屬性設定為,然后FLAG_ACTIVITY_NEW_TASK僅啟動它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/365264.html
