1

I am testing creating a game loop without using surface view, but I cannot get the thread to run continuously. In the code below, I am expecting the text view to show the decreasing number continuously, but it only shows it once.

public class ActivityGameTest extends AppCompatActivity {
int bigNumber = Integer.MAX_VALUE;
Thread gameThread;
TextView myText;
private Handler uiHandler;
boolean mRun;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game_test);
    myText = (TextView) findViewById(R.id.txtHello);
    uiHandler = new Handler();

    gameThread = new Thread(null, processFrame, "ProcessFrame");
    mRun = true;
    gameThread.start();
}

private Runnable processFrame = new Runnable() {

    @Override
    public void run() {
        while (mRun) {
            updateFrame();

//EDIT - adding these lines

try {
                sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }
};

private void updateFrame() {
    bigNumber--;
    uiHandler.post(showFrame);
}

private Runnable showFrame = new Runnable() {
    @Override
    public void run() {
        myText.setText(Integer.toString(bigNumber));
    }
};

}

NiMuSi
  • 382
  • 1
  • 4
  • 15
  • This code is working for me. Did you find the solution for your problem ? Maybe you can use a sleep in the thread and test it really works. – Krish Jun 27 '17 at 08:34
  • Thanks @Krish Adding the sleep resolves the issue, but why? – NiMuSi Jun 27 '17 at 19:54
  • Since you are updating the UI in a infinite loop without any delay , the UI thread will be too busy to update the Textview and will skip the frames. So that you cant see the changes. – Krish Jun 28 '17 at 07:29
  • Thanks very much Krish, Please add that as an answer so I can accept it. – NiMuSi Jun 28 '17 at 09:02

1 Answers1

0

Updates to the UI should be run on UI thread in android… As pointed out here, you can wrap the call to the android ui thread in a function and call it when needed.

deHaar
  • 17,687
  • 10
  • 38
  • 51