Implementing a while loop in android

后端 未结 1 1977
独厮守ぢ
独厮守ぢ 2021-01-30 19:08

I can\'t understand the implementation of a while loop in android.

Whenever I implement a while loop inside the onCreate() bundle, (code shown below)

<
相关标签:
1条回答
  • 2021-01-30 19:19

    Brace yourself. And try to follow closely, this will be invaluable as a dev.

    While loops really should only be implemented in a separate Thread. A separate thread is like a second process running in your app. The reason why it force closed is because you ran the loop in the UI thread, making the UI unable to do anything except for going through that loop. You have to place that loop into the second Thread so the UI Thread can be free to run. When threading, you can't update the GUI unless you are in the UI Thread. Here is how it would be done in this case.

    First, you create a Runnable, which will contain the code that loops in it's run method. In that Runnable, you will have to make a second Runnable that posts to the UI thread. For example:

     TextView myTextView = (TextView) findViewById(R.id.myTextView); //grab your tv
     Runnable myRunnable = new Runnable() {
          @Override
          public void run() {
               while (testByte == 0) {
                    Thread.sleep(1000); // Waits for 1 second (1000 milliseconds)
                    String updateWords = updateAuto(); // make updateAuto() return a string
                    myTextView.post(new Runnable() { 
                         @Override
                         public void run() {
                              myTextView.setText(updateWords);
                         });
               }
          }
     };
    

    Next just create your thread using the Runnable and start it.

     Thread myThread = new Thread(myRunnable);
     myThread.start();
    

    You should now see your app looping with no force closes.

    0 讨论(0)
提交回复
热议问题