首页 > 解决方案 > 无法停止线程执行 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()


    }

标签: androidmultithreadingkotlin

解决方案


推荐阅读