英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论