如何在每次Android启动或重新启动时使用Kotlin生成随机数?

huangapple go评论55阅读模式
英文:

How can I generate a random number each time the android starts up or restarted, using Kotlin?

问题

我尝试使用以下代码:
var testNumber: Int = (0..4).random()
我还尝试了以下代码:
var testNumber: Int = Random.nextInt(0, 5)
然而,每次运行应用程序时生成的数字都保持不变。

英文:

I've tried using the following code:
var testNumber: Int = (0..4).random()
I also attempted the following code:
var testNumber: Int = Random.nextInt(0, 5)
However, the generated number remains the same whenever I run the app.

答案1

得分: 0

您正在使用哪个版本的Kotlin?1.6.21(可能是在1.5之后的其他版本也存在此问题)存在一个bug,其中某些Android版本在重启后会产生相同的“随机”序列,这是因为Android处理ThreadLocalRandom的方式。

如果您使用受影响的版本,请尝试将Kotlin Gradle插件升级至至少1.7.20。如果由于某种原因无法升级,请考虑使用java.util.random.Random作为随机性的源。

英文:

What version of Kotlin are you using? There's a bug in 1.6.21 (and possibly other versions after 1.5) where some versions of Android produce the same "random" sequences after a reboot, because of how Android handles ThreadLocalRandom.

If you're using an affected version, try upgrading your Kotlin Gradle plugin to at least 1.7.20. If you can't do that for whatever reason, you might want to use java.util.random.Random as a source of randomness instead

huangapple
  • 本文由 发表于 2023年5月25日 16:18:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定