TextView doesn't synchronize

2019-09-02 10:44发布

问题:

I'm building my first App and simple game similar to MasterMind with numbers. I would that when the pc try to find my number, don't show immediately all the attempts that he does before finding the correct number, but that he does it gradually. For example the CPU say the first number, wait one second and then say the second number and so on. Here is the code:

public void startCPU() {
    int num;
    int strike;
    int xx;

    do {
        do {
            Random random = new Random();
            num = random.nextInt((9876 - 123) + 1) + 123;
            xx = (int) numpos.pox[num];
        } while (xx == 0);

        Numeri.Confronta(mioNumero, numpos.pox[num]);

        int ball = Risultati.getBall();
        strike = Risultati.getStrike();
        TextView txtv = (TextView) findViewById(R.id.numberthatcpusay);

        if (numpos.pox[num] < 1000) {
            Integer x = numpos.pox[num];
            String s = ("0" + Integer.toString(x) + " " + Integer.toString(strike) + "X "
                    + Integer.toString(ball) + "O" + "  ");
            txtv.append(s);

        } else {
            Integer x = numpos.pox[num];
            String s = (Integer.toString(x) + " " + Integer.toString(strike) + "X "
                    + Integer.toString(ball) + "O" + "   ");
            txtv.append(s);
        }

        numeroDato = numpos.pox[num];
        numpos.pox[num] = 0;
        for (int i = 0; i <= 9876; i++) {
            if (Risultati.checkStrikeAndBall(numeroDato, numpos.pox[i], strike, ball) == true) {
                numpos.pox[i] = 0;
            }
        }

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

    } while (strike != 4);

    startMe();
}

The problem is that the textView don't update every second but he update only when the CPU have found the number. In this way when I click on the button that launch this mehtod the time that I should wait before i see the results is equal at the number of the attemps. For example, if the CPU needs 9 number before he found the correct number I should wait 9 seconds before the textView show all the attempts. How can I resolve it?

回答1:

You can't do that on the UI thread!

You're running a loop that calls Thread.sleep() on the UI thread, which basically freezes the phone completely.

Consider using an AsyncTask.

in the doInBackground method you're not on the UI thread, so you can call sleep. and every second calculate the new number and call publishProgress to update the UI. Then in the onProgressUpdate callback, you do the TextView.append() call - because it must be called on the UI thread.