java – Android Thread. start()CalledFromWrongThreadException

I'm not sure if my prompt is correct because I didn't get the expected output I have a class in which I invoke a way to start a thread.

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {
beginListenForData()
}

The beginlistenfordata function is used to start a thread and check whether data is available for reading If this is the case, it reads and updates the UI variables:

void beginListenForData()
{
    Thread workerThread = new Thread(new Runnable() {
        @Override
        public void run()
        {    
            int bytesAvailable = 3;
            while(!Thread.currentThread().isInterrupted())
            {
                try
                {
                    bytesAvailable = mmInStream.available();
                    if(bytesAvailable > 0)
                    {
                        byte[] packetBytes = new byte[bytesAvailable];
                        mmInStream.read(packetBytes);
                bytesAvailable = mmInStream.available();
                String s = new String(packetBytes);
                text.setText(s);
                    }
                }
                catch (Exception e)
                {
            // TODO Auto-generated catch block
                e.printStackTrace();
                }
            }
        }
    });

       workerThread.start();
   }

}

I didn't get the required output The thread should read the data or check whether the data is available If available, read it and set the UI variable to the read value

Did I execute it correctly? Is there anything wrong with my code?

Solution

Thread failed to update GUI

How to use an Android handler to update a textview in the UI thread?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>