【问题标题】:Receiving explicit intents while activity is in the foreground在活动处于前台时接收明确的意图
【发布时间】:2020-08-16 12:17:25
【问题描述】:

我的应用有一项活动和一项服务。该服务启动一个前台通知,该通知有一个操作按钮,在某些情况下需要告诉活动做一些事情,而不仅仅是回到前面。它使用 Extras 来表明这一点。

我的问题是,除了通过传递给 onCreate() 的“bundle”之外,我找不到任何关于如何接收显式意图的文档,因为该活动可能已经创建,因此通常不会被调用。

在 onCreate() 之后如何收到一个意图?

通知码sn-p:

    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())

【问题讨论】:

    标签: android android-intent android-service android-notifications android-pendingintent


    【解决方案1】:

    覆盖onNewIntent()。如果 Activity 已经存在,并且 Intent 将其带回前台,则 Intent 将传递给 onNewIntent()

    【讨论】:

    • 只有在 onCreate() 不是时才调用它吗? IE。我需要处理这两个地方的意图吗?
    • @kkemper:“我需要处理这两个地方的意图吗?” ——通常,是的。一种常见的方法是使用一个从onCreate()(传递getIntent())和onNewIntent()(传递给IntentonNewIntent())调用的函数,以减少代码重复。
    猜你喜欢
    • 2014-12-07
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多