【问题标题】:What does requestCode represent?requestCode 代表什么?
【发布时间】:2022-01-20 17:37:42
【问题描述】:

我认为 requestCode 是某种标识符,仅需要 Intent 或类似的东西,如果我错了,请纠正我。但如果是这种情况,为什么如果我的 pendingintent 的 requestCode 为 2,当我将 requestcode 作为 0 传递时,它的行为会有所不同。我没有另一个pendingintent,其中将 2 作为 requestcode 传递。

假设我启动我的应用程序,然后我收到一个通知,当我单击此通知时...

requestCode = 2 ...一个新的活动被创建并被带到前台,当我按下后退按钮时,我会回到我在退出应用程序之前处于相同状态的活动

请求代码 = 0 ...我直接回到我在退出应用程序之前处于相同状态的活动。未创建新活动

这并不是一个真正的大问题,我可以传递 0 并且应用程序将按照我想要的方式运行,但我只是想知道为什么会发生这种情况。

在 MainActivity.kt

    private fun startAlarm (cal : Calendar){
        val alarmManager :AlarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
        val intent = Intent (this, AlertReceiver().javaClass)
        val pendingIntent : PendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0)
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.timeInMillis, pendingIntent)
    }
}

AlertReceiver.kt

class AlertReceiver(): BroadcastReceiver() {

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onReceive(context: Context?, intent: Intent?) {
        val notificationObj : Notification = Notification(context)
        val notif : NotificationCompat.Builder = notificationObj.createNotification()

        notificationObj.getManager().notify(1, notif.build())
    }
}

在 Notification.kt 中

fun createNotification(): NotificationCompat.Builder{
        val main: Intent = Intent (this, MainActivity().javaClass).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        //-------------------talking about this line--------------------------------
        val pendingMain: PendingIntent = PendingIntent.getActivity(this, 2, main, 0)
        val notif : NotificationCompat.Builder = NotificationCompat.Builder(applicationContext, channelID)
            .setSmallIcon(R.drawable.ic_android_black_24dp)
            .setContentTitle("test:")
            .setContentText("testing")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingMain)
            .setAutoCancel((true))

        return notif
    }

【问题讨论】:

  • 我不确定我是否完全遵循了您的问题,但 requestCode 应该对您的活动开始的如何没有影响。它只是一个 ID,您可以根据需要在 Activity 中签入。也许您正在更改意图标志?
  • 我也是这么想的,我也不认为requestCode会真正影响它。但似乎当我从任何非 0 更改请求代码时,每当我单击通知时,它都会在原始副本之上创建一个新的活动副本。我已经测试了很多次,除了请求代码之外,没有触及代码中的任何内容。有点奇怪
  • 您使用的是Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK,所以无论requestCode如何,我都会期待一个新的活动。
  • 您是否在代码中的任何其他位置创建了任何PendingIntent,并将MainActivity 作为目标?因为你的解释根本没有意义。由于您使用了标志NEW_TASKCLEAR_TASK,因此行为不应该是您描述的两种情况。另外,请编辑您的问题并从问题的清单中粘贴相关的<activity> 声明。

标签: android android-studio kotlin android-pendingintent


【解决方案1】:

当您使用 onActivityResult() 将数据从多个 Fragment 传递到 Activity 时,该 Activity 通过请求代码识别子 Fragment

【讨论】:

    猜你喜欢
    • 2016-01-24
    • 2014-02-26
    • 2016-01-27
    • 2019-08-13
    • 1970-01-01
    • 2012-11-07
    • 2013-12-26
    • 2014-09-02
    • 2015-11-18
    相关资源
    最近更新 更多