我的应用程序只有一个活动和一个服务。该服务启动前台通知,该通知具有一个操作按钮,在某些情况下需要除了返回前台之外告诉活动执行其他操作的功能。它使用Extras来表示这个操作。
我的问题是,我找不到任何关于如何接收显式意图的文档,除了通过传递给onCreate()
的“bundle”之外,这通常不被调用,因为活动可能已经被创建。
在onCreate()
之后如何接收意图?
通知代码片段:
val actionIntent = Intent(this, MainActivity::class.java)
actionIntent.action = actionText
actionIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP
val pendingActionIntent: PendingIntent = PendingIntent.getActivity(this, 0, actionIntent, 0)
val actionCancel: NotificationCompat.Action = NotificationCompat.Action.Builder(R.drawable.ic_cancel_black_24dp,
actionText,
pendingActionIntent).build()
val notificationBuilder: NotificationCompat.Builder = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setContentTitle(getText(R.string.notification_title))
.setSmallIcon(R.drawable.ic_logo_24dp)
.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true)
.addAction(actionCancel)
.setContentText(text)
startForeground(ONGOING_NOTIFICATION_ID, notificationBuilder.build())
onCreate()
中调用它(传递getIntent()
),并在onNewIntent()
中调用它(传递给onNewIntent()
的Intent
),以减少代码重复。 - CommonsWare