当活动处于前台时接收显式意图

3

我的应用程序只有一个活动和一个服务。该服务启动前台通知,该通知具有一个操作按钮,在某些情况下需要除了返回前台之外告诉活动执行其他操作的功能。它使用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())
1个回答

2

重写 onNewIntent() 方法。如果活动已经存在,并且一个 Intent 将其带回前台,那么该 Intent 将被传递给 onNewIntent() 方法。


这只有在onCreate()没有被调用时才会被调用吗?也就是说,我需要在两个地方处理意图吗? - kkemper
1
@kkemper:“我需要在两个地方都处理意图吗?”-通常是这样的。一种常见的方法是拥有一个单独的函数,你可以在onCreate()中调用它(传递getIntent()),并在onNewIntent()中调用它(传递给onNewIntent()Intent),以减少代码重复。 - CommonsWare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接