简体   繁体   English

Android应用程序在线程中调用方法后崩溃?

[英]Android App Crashing after calling method in a thread?

Currently in my Android Game there is a simple thread that runs, decreasing a horizontal progressbar by 1 every X milliseconds. 目前在我的Android游戏中有一个简单的线程运行,每X毫秒将水平进度条减少1。 I'm trying to implement a method so when the progressbar hits 0, a TextView changes to "Game Over". 我正在尝试实现一个方法,所以当进度条达到0时,TextView会变为“Game Over”。 The app crashes whenever this function is called in this way . 只要以这种方式调用此函数,应用程序就会崩溃 I have also initialized the variable correctly so the method should have no trouble seeing this TextView. 我还正确初始化了变量,因此该方法应该可以毫无困难地看到这个TextView。

  public class MyThread extends Thread{ @Override public void run(){ while (counter > 0 && keepRunning){ counter = counter - 1; android.os.SystemClock.sleep(calculateSleepTick()); mHandler.post(new Runnable() { @Override public void run() { progressTest.setProgress(counter); } }); } isGameOver(); } } 

  public void isGameOver(){ scoreText.setText("Game Over"); } 

Your isGameOver function sets the text of a UI element. 您的isGameOver函数设置UI元素的文本。 You can't call functions of UI elements on a thread other than main. 您不能在main之外的线程上调用UI元素的函数。 It needs to be posted to the UI thread to do that. 需要将其发布到UI线程才能执行此操作。

You cannot update UI in non UI threads. 您无法在非UI线程中更新UI。 Call isGameOver() this way. 以这种方式调用isGameOver()

runOnUiThread(new Runnable() { @Override public void run() { isGameOver(); } });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM