Android在子线程(Thread)中使用Toast

只需在Toast的前后加上:Looper.prepare(); 与Looper.loop();  即可。

Thread readThread=new Thread() {
   @Override
   public void run() {
      super.run();
      while (!isExits) {
         try {
            Thread.sleep(50);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
         if (ch340AndroidDriver != null) {
            byte[] readBuffer = new byte[BUF_SIZE];
            if (ch340AndroidDriver.ReadData(readBuffer, LENGTH) > 0) {
               Message msg = new Message();
               msg.what = MSG_USB_GETDATA;
               msg.obj = readBuffer;
               handler.sendMessage(msg);
               isGet = true;
               Log.e(TAG, "read success:"
                     + bytes2HexString(readBuffer));
               /*Looper.prepare();
               Toast.makeText(MainActivity.this,
                     "读取的数据值为:"+ bytes2HexString(readBuffer),
                     Toast.LENGTH_LONG).show();
               Looper.loop();*/
            } else {
                     /*Log.e(TAG, "read failed");*/
               isGet = false;
            }
         }
      }
   }
};
   

但是其实不建议使用,我使用的就导致线程不能一直正常执行,因为我只是用Toast用来调试数据是否正确的,还是改成了用Log日志形式调试


你可能感兴趣的:(Android在子线程(Thread)中使用Toast)