android - 无法停止线程执行 onPause 并恢复执行 onResume
问题描述
我对编码比较陌生。我正在开发一个具有多种模式的乒乓球游戏,例如简单、困难等。我创建了一个名为 gameboard 的 customView,如下所示-
class GameBoard : View {
@Volatile var gameOn = false
//several member variables
fun start(){
gameOn = true
GameThread().start()
}
fun stop(){
gameOn = false
}
inner class GameThread : Thread()
{
override fun run()
{
while (gameOn) {
//do some processes
if (ballOutsideRange) {
gameOn = false
}
}
}
}
}
我的主要活动如下 -
class MainActivity : AppCompatActivity() {
private lateinit var mGameBoard:GameBoard
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_MainActivity)
this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
mGameBoard = GameBoard(this.applicationContext)
mGameBoard.setMode("easy")
}
override fun onResume() {
mGameBoard.gameOn = true
super.onResume()
//mGameBoard.start()
}
override fun onPause() {
mGameBoard.gameOn = false
super.onPause()
}
}
当主要活动进入后台时,游戏继续。我期待游戏停止,因为我将 gameOn 变量设置为 false。我也从 customView 游戏板 onSizeChanged 调用线程 start(),如下所示。我不得不从那里调用函数 start() 因为这是我得到 customView 的正确高度和宽度的地方-
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mWidth = width
mHeight = height
cxBall = (Random.nextInt(1, mWidth)).toFloat()
cyBall = (mHeight/6).toFloat()
cxPaddle = (width/2 - PADDLE_WIDTH/2).toFloat()
paintScoreText.textSize = height / 20f
paintHighScoreText.textSize = height / 20f
start()
}
解决方案
推荐阅读
- java - SDN6 - 带有属性映射的投影接口
- apache - .htaccess 不重写现有文件
- javascript - 使用 document.getElementByID 时如何添加换行符
- node.js - 如何将工作表导出为 pdf 并将其上传到一个特定的文件夹中?
- json - 如何以typesense存储带有键值的数组
- javascript - 单击资源管理器上的后/前按钮时,重定向不正确。我在 scala 中使用游戏框架
- webhooks - 当 Azure 容器注册表中的新映像通过 Webhook 发送到 MS Teams 时,如何在 MS Teams 频道中通知
- amazon-cloudfront - ERROR 验证错误:Lambda 函数结果验证失败,函数尝试删除只读标头,标头名称:Content-Length
- wordpress - 将电子邮件和电话字段添加到 Woocommerce 分析订单报告
- django - 脚本运行 30 秒后出现 nginx 错误