我认为requestCode是某个Intent刚被调用时的标识符,如果我理解错了,请纠正我。但如果是这样的话,为什么如果我的pendingintent的requestCode为2时,当我传递0作为requestCode时,它会有所不同呢?我没有另一个pendingintent传递了2作为requestCode。
假设我启动我的应用程序,然后我收到了一个通知,在我单击此通知时...
requestCode = 2 ...将创建一个新的活动并置于前景,当我按下返回按钮时,我回到了同一状态下的相同活动在应用程序退出之前。
requestCode = 0 ...我直接回到了同一个活动,在应用程序退出之前处于相同的状态。不会创建新的活动。
这不是一个很大的问题,我可以传递0,应用程序将按照我想要的方式工作,但我只是想知道为什么会发生这种情况。
在MainActivity.kt中:
在 Notification.kt 中:
假设我启动我的应用程序,然后我收到了一个通知,在我单击此通知时...
requestCode = 2 ...将创建一个新的活动并置于前景,当我按下返回按钮时,我回到了同一状态下的相同活动在应用程序退出之前。
requestCode = 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
}
Intent.FLAG_ACTIVITY_NEW_TASK
或Intent.FLAG_ACTIVITY_CLEAR_TASK
,因此我期望无论 requestCode 是什么,都会启动一个新的 Activity。 - dominicoderMainActivity
作为目标创建任何PendingIntent
?因为你的解释根本没有意义。由于你使用了NEW_TASK
和CLEAR_TASK
标志,行为应该不是你描述的两种情况之一。另外,请编辑你的问题并将清单中相关的<activity>
声明粘贴到问题中。 - David Wasser